Last active
May 22, 2016 03:02
-
-
Save daniellizik/f7cc2d5f8f45b1bb1301c8003a8ec313 to your computer and use it in GitHub Desktop.
needle/haystack deep search, searches for value if it matches a key and will stop execution once found.
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
'use strict'; | |
function deepsearch_find_first(needle, haystack, parent) { | |
let iterable; | |
if (Object.prototype.toString.call(haystack) === '[object Array]') { | |
iterable = haystack; | |
} else if (Object.prototype.toString.call(haystack) === '[object Object]') { | |
iterable = Object.keys(haystack); | |
} else if (needle === haystack) { | |
return parent; | |
} else { | |
return; | |
} | |
for (let i = 0; i < iterable.length; i++) { | |
let key = haystack.hasOwnProperty(iterable[i]) ? haystack[iterable[i]] : iterable[i]; | |
let found = deepsearch_find_first(needle, key, haystack); | |
if (found) | |
return found; | |
} | |
} | |
var fixture = { | |
a: { | |
a1: 'df', | |
a2: 'dlkfj', | |
b: { | |
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('cat', fixture); | |
console.log(typeof result === 'object', 'result should return object'); | |
console.log(result.hasOwnProperty('a'), 'result should have a key'); | |
console.log(result.a === 'cat', 'result should have cat val'); |
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
var fixture = { | |
a: { | |
a1: 'df', | |
a2: 'dlkfj', | |
b: { | |
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('cat', fixture); | |
console.log(typeof result === 'object', 'result should return object'); | |
console.log(result.hasOwnProperty('a'), 'result should have a key'); | |
console.log(result.a === 'cat', 'result should have cat val'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment