You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
828 B
JavaScript
36 lines
828 B
JavaScript
"use strict";
|
|
|
|
const { validateOptions, required, isFunction, isString } = require("validatem");
|
|
const assureArray = require("assure-array");
|
|
const isIterable = require("is-iterable");
|
|
|
|
module.exports = function findInTree(options) {
|
|
validateOptions(arguments, {
|
|
tree: [ required ],
|
|
predicate: [ required, isFunction ],
|
|
childrenProperty: [ isString ],
|
|
});
|
|
|
|
let childrenProperty = options.childrenProperty ?? "children";
|
|
let topLevelItems = assureArray(options.tree);
|
|
let predicate = options.predicate;
|
|
|
|
function find(items) {
|
|
if (isIterable(items)) {
|
|
for (let item of items) {
|
|
if (predicate(item)) {
|
|
return item;
|
|
} else {
|
|
let childResult = find(item[childrenProperty]);
|
|
|
|
if (childResult !== undefined) {
|
|
return childResult;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return find(topLevelItems);
|
|
};
|