From 2cbaea7796a1e3f5ed2fb7614f1f41e1be63b7cc Mon Sep 17 00:00:00 2001 From: Pavel Kilin Date: Sat, 12 Sep 2015 12:00:55 +0600 Subject: [PATCH] Added `check` option --- README.md | 30 ++++++++++++++++++++++++++++++ index.js | 3 ++- test/test.js | 18 ++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e4cb3c..d968104 100644 --- a/README.md +++ b/README.md @@ -158,3 +158,33 @@ flatten({ // 'key3.a': { b: { c: 2 } } // } ``` + +### check + +Check value for some condition. If returns `true` value will be flattened. + +```javascript +var flatten = require('flat') + +flatten({ + hello: { + world: { + again: 'good morning' + }, + everyone: { + again: 'good evening' + } + } +}, { + check: function(value) { + return value.again != 'good morning' + } +}) + +// { +// 'hello.world': { +// again: 'good morning' +// }, +// 'hello.everyone.again': 'good evening' +// } +``` diff --git a/index.js b/index.js index 4d6914a..964bbaf 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ function flatten(target, opts) { var maxDepth = opts.maxDepth var currentDepth = 1 var output = {} + var check = opts.check || function() {return true} function step(object, prev) { Object.keys(object).forEach(function(key) { @@ -29,7 +30,7 @@ function flatten(target, opts) { maxDepth = currentDepth + 1; } - if (!isarray && !isbuffer && isobject && Object.keys(value).length && currentDepth < maxDepth) { + if (!isarray && !isbuffer && isobject && check(value) && Object.keys(value).length && currentDepth < maxDepth) { ++currentDepth return step(value, newKey) } diff --git a/test/test.js b/test/test.js index 707901b..f660a00 100644 --- a/test/test.js +++ b/test/test.js @@ -154,6 +154,24 @@ suite('Flatten', function() { } }) }) + + test('Custom Checker', function() { + assert.deepEqual(flatten({ + hello: { + world: { + again: 'good morning' + }, + everyone: { + again: 'good evening' + } + } + }, {check: function(value) {return value.again != 'good morning'}}), { + 'hello.world': { + again: 'good morning' + }, + 'hello.everyone.again': 'good evening' + }) + }) }) suite('Unflatten', function() {