Last active
May 18, 2016 17:52
-
-
Save daniellizik/a849ead8c3fc041b6dff5fc8942f86a0 to your computer and use it in GitHub Desktop.
searches haystack for needle and returns array of tree nodes from correct path
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
function pathfinder(needle, haystack, child = haystack, parent, result = [], path = [], paths = [[[haystack]]], siblingIndex = 0, depthIndex = 0, rootIndex, onRoot) { | |
let iterable = []; | |
if (Object.prototype.toString.call(child) === '[object Array]') { | |
iterable = child; | |
} else if (Object.prototype.toString.call(child) === '[object Object]') { | |
iterable = Object.keys(child); | |
} | |
if (onRoot === true) { | |
paths.push(paths[0]); | |
} | |
if (depthIndex > 0) { | |
let path = paths[rootIndex].slice(); | |
path.push(child); | |
// paths[rootIndex].push(path); | |
console.log(path, paths) | |
// console.log('root', rootIndex, 'depth', depthIndex, 'sibling', siblingIndex, paths[rootIndex]) | |
} | |
if (child === needle) { | |
result.push(paths[rootIndex]); | |
} | |
for (let i = 0; i < iterable.length; i++) { | |
pathfinder( | |
needle, | |
haystack, | |
child.hasOwnProperty(iterable[i]) ? child[iterable[i]] : iterable[i], | |
child, | |
result, | |
path, | |
paths, | |
i, | |
depthIndex + 1, | |
depthIndex === 0 ? i : rootIndex, | |
rootIndex === undefined | |
); | |
} | |
return [].concat.apply([], result); | |
} | |
var f = { | |
"a": "a", | |
"b": "b", | |
"b2": null, | |
"b3": ["b3.0", "b3.1", "b3.2"], | |
"c": { | |
"c1": [ | |
"c1.1", | |
"c1.2", | |
"c1.3", | |
"c1.4", | |
{ | |
"c2": "fake", | |
"c2b": [ | |
"c2b.a", | |
"c2b.b", | |
"c2b.c", | |
false, | |
{ | |
"c4": "needle" | |
} | |
] | |
}, | |
{ | |
"c3": "false" | |
} | |
] | |
}, | |
"d": { | |
"d1": { | |
"d2": "d2", | |
"d3": { | |
"d4": { | |
"d5": [ | |
"d6.0", | |
{ | |
"d7": "this is d7" | |
} | |
] | |
} | |
} | |
} | |
}, | |
"e": "e is null" | |
}; | |
var res = pathfinder('needle', f); | |
console.log(res); | |
// console.log(res.length === 6, 'res should have 6 nodes'); | |
// console.log(res.filter(n => typeof n === 'object').length === res.length, 'nodes can only be objects'); | |
// console.log(JSON.stringify(res[0]) === JSON.stringify(f), 'first node should be root object'); | |
// console.log(JSON.stringify(res[res.length - 1]) === JSON.stringify({c4: 'needle'}), 'last node should be needle object'); | |
/* | |
// result | |
[ | |
// root level path container | |
[ | |
// individual path array | |
[{}, {}, {}, result] | |
] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment