Skip to content
Permalink
Browse files Browse the repository at this point in the history
[fix] Don't pollute prototype
  • Loading branch information
piranna committed Aug 14, 2020
1 parent 8b9f396 commit 53c61a8
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 12 deletions.
34 changes: 22 additions & 12 deletions index.js
Expand Up @@ -5,17 +5,6 @@ function reducer(result, arg)
// Get key node
const keypath = arg.shift().split('.')

let key = keypath.shift()
let node = result

while(keypath.length)
{
node[key] = node[key] || {}
node = node[key]

key = keypath.shift()
}

// Get value
let val = true
if(arg.length)
Expand All @@ -24,8 +13,29 @@ function reducer(result, arg)
if(val.length === 1) val = val[0]
}

let key = keypath.shift()

if(!keypath.length) return {...result, [key]: val}

if(!result.hasOwnProperty(key)) result = {...result, [key]: {}}

let newKey
let newNode
let node = result

while(true)
{
newKey = keypath.shift()
newNode = node[key]

if(!keypath.length) break

node = node[key] = {...newNode, [newKey]: newNode[newKey] || {}}
key = newKey
}

// Store value
node[key] = val
node[key] = {...newNode, [newKey]: val}

return result
}
Expand Down
15 changes: 15 additions & 0 deletions test.js
Expand Up @@ -19,3 +19,18 @@ const expected =
const result = linuxCmdline(cmdline)

deepStrictEqual(result, expected)


// Don't pollute prototype
const result2 = linuxCmdline('__proto__.polluted=foo')
const expected2 =
{
['__proto__']:
{
polluted: 'foo'
}
}

deepStrictEqual(result2, expected2)

deepStrictEqual({}.__proto__.polluted, undefined)

0 comments on commit 53c61a8

Please sign in to comment.