Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Last active January 21, 2019 10:26
Show Gist options
  • Save Akiyamka/4d878f8b174bfacd3d40db382e2b56b3 to your computer and use it in GitHub Desktop.
Save Akiyamka/4d878f8b174bfacd3d40db382e2b56b3 to your computer and use it in GitHub Desktop.
/**
* 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