From f49340f066005fc8276c268db9824e9cfc85b003 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9=20=D0=9C=D0=B0?= =?UTF-8?q?=D1=82=D0=B0=D1=81=D0=BE=D0=B2?= Date: Thu, 27 Jul 2017 13:40:01 +0300 Subject: [PATCH] maxDepth for unflatten --- index.js | 13 ++++++++++++- test/test.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index ca8904a..52a1678 100644 --- a/index.js +++ b/index.js @@ -44,8 +44,13 @@ function flatten (target, opts) { function unflatten (target, opts) { opts = opts || {} + if (opts.maxDepth === 0) { + return target + } + var delimiter = opts.delimiter || '.' var overwrite = opts.overwrite || false + var maxDepth = opts.maxDepth || Infinity var result = {} var isbuffer = isBuffer(target) @@ -75,6 +80,7 @@ function unflatten (target, opts) { var key1 = getkey(split.shift()) var key2 = getkey(split[0]) var recipient = result + var depth = 1 while (key2 !== undefined) { var type = Object.prototype.toString.call(recipient[key1]) @@ -96,13 +102,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) }) diff --git a/test/test.js b/test/test.js index 541c9d7..c4924e1 100644 --- a/test/test.js +++ b/test/test.js @@ -205,6 +205,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.deepEqual({ hello: {