Skip to content

Instantly share code, notes, and snippets.

@daniellizik
Created May 17, 2016 03:54
Show Gist options
  • Save daniellizik/47b99c0040ffce9c4dcf6f9dbdd6fb9d to your computer and use it in GitHub Desktop.
Save daniellizik/47b99c0040ffce9c4dcf6f9dbdd6fb9d to your computer and use it in GitHub Desktop.
deepsearch find first, make path
function deepsearch_find_first_make_path(needle, haystack, delimiter = '.', path = []) {
let i = 0;
let p;
let found;
if (Object.prototype.toString.call(haystack) === '[object Array]') {
for (i; i < haystack.length; i++) {
found = deepsearch_find_first_make_path(needle, haystack[i], delimiter, path.concat(i));
if (found && found !== path) {
return found;
}
}
}
else if (Object.prototype.toString.call(haystack) === '[object Object]') {
for (p in haystack) {
found = deepsearch_find_first_make_path(needle, haystack[p], delimiter, path.concat(p));
if (found && found !== path) {
return found;
}
}
}
else if (haystack === needle) {
return path.join(delimiter);
}
}
var fixture = {
a: {
berf: {
c: {
d: {
e: {
f: 'mouse'
}
}
},
g: [
5,
45,
true,
null,
false,
5643635,
{
a: {
b: {
c: {
d: 'horse'
}
}
},
f: [
{},
{},
[],
undefined,
{
a: 'cat'
}
]
}
]
}
}
};
var result = deepsearch_find_first_make_path('cat', fixture, '.');
console.log(typeof result === 'string', 'result should return string');
console.log(result === 'a.berf.g.6.f.4.a', 'result should return path');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment