I wanted to write a function findDeep that would perform a recursive, depth-first search on plain objects and arrays.
Comments and criticism welcome.
function findDeep(dict, test, index = 0, keys = Object.keys(dict)) {
var item = dict[keys[index]];
if(index > keys.length) {
return null; // End of siblings. No match.
}
if(test(item)) {
return item; // Match.
}
if(item !== null && typeof item === 'object') { // null is an object.
var result = findDeep(item, test); // Children.
if(result) {
return result; // Short circuit, when item found.
}
}
return findDeep(dict, test, ++index); // Siblings.
}
document.writeln('test1: ', findDeep(['foo', 'bar', 'bam'], i => i === 'bar') === 'bar', '<br/>')
document.writeln('test2: ', findDeep([ ['foo'], [['bar']], [ ['baz', ['bat'] ] ] ], i => i === 'bat') === 'bat', '<br/>');
document.writeln('test3: ', findDeep({ foo: 'foo', bar: 'bar', bam: { baz: 'baz' } }, i => i === 'baz') === 'baz', '<br/>');
undefined
problem. This solution will only return the first match. \$\endgroup\$