Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

maxDepth for unflatten #59

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,14 @@ function flatten (target, opts) {
function unflatten (target, opts) {
opts = opts || {}

if (opts.maxDepth === 0) {
return target
}

const delimiter = opts.delimiter || '.'
const overwrite = opts.overwrite || false
const transformKey = opts.transformKey || keyIdentity
const maxDepth = opts.maxDepth || Infinity
const result = {}

const isbuffer = isBuffer(target)
Expand All @@ -80,7 +85,6 @@ function unflatten (target, opts) {
function addKeys (keyPrefix, recipient, target) {
return Object.keys(target).reduce(function (result, key) {
result[keyPrefix + delimiter + key] = target[key]

return result
}, recipient)
}
Expand Down Expand Up @@ -119,6 +123,7 @@ function unflatten (target, opts) {
let key1 = getkey(split.shift())
let key2 = getkey(split[0])
let recipient = result
let depth = 1

while (key2 !== undefined) {
if (key1 === '__proto__') {
Expand All @@ -144,13 +149,18 @@ function unflatten (target, opts) {
}

recipient = recipient[key1]
if (split.length > 0) {
if (split.length > 0 && depth < maxDepth) {
key1 = getkey(split.shift())
key2 = getkey(split[0])
} else {
key1 = getkey(split.join(delimiter))
key2 = undefined
}
depth += 1
}

// unflatten again for 'messy objects'
opts.maxDepth -= depth
recipient[key1] = unflatten(target[key], opts)
})

Expand Down
45 changes: 45 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,51 @@ suite('Unflatten', function () {
}))
})

test('Custom Depth', function () {
assert.deepEqual(unflatten({
'hello.brave': {
'new.world.again': 'good morning'
},
'all.you.need.is.love': 'love is all you need'
},
{
maxDepth: 3
}), {
hello: {
brave: {
'new': {
'world.again': 'good morning'
}
}
},
all: {
you: {
need: {
'is.love': 'love is all you need'
}
}
}
})
})

test('Zero Depth', function () {
assert.deepEqual({
hello: {
world: {
again: 'good morning'
}
}
}, unflatten({
hello: {
world: {
again: 'good morning'
}
}
}, {
maxDepth: 0
}))
})

test('Multiple Keys', function () {
assert.deepStrictEqual({
hello: {
Expand Down