Last active
January 21, 2019 10:26
-
-
Save Akiyamka/4d878f8b174bfacd3d40db382e2b56b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Find branch in tree by omen pair - key-value | |
* @param {Object} omen - how to find branch. Example - { id: 123456 } | |
* @param {Object} options [{children: 'children', returnChild: true}]; | |
* @param {Boolean} options.returnChild - | |
* if true return branch started from found child, | |
* else return whole branch where child founded | |
*/ | |
function findBranchByOmen(omen, options) { | |
const [[omenProp, omenValue]] = Object.entries(omen); | |
const opt = { | |
children: 'childrens', | |
returnChild: true, | |
...opt | |
}; | |
function _findBranch(tree) { | |
if (omenValue === tree[omenProp]) return tree; | |
if (!tree[opt.children]) return false; | |
return opt.returnChild | |
? tree[opt.children].reduce((result, branch) => _findBranch(branch) || result, false) | |
: tree[opt.children].find(branch => _findBranch(branch)); | |
} | |
return data => _findBranch(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment