Last active
December 31, 2015 03:59
-
-
Save amatiasq/7931209 to your computer and use it in GitHub Desktop.
Dirty code than recursively analyzes a object for a specific string without using recursive functions because of call stack limit.
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 find(term, obj, name) { | |
var key = '!"·$% &/()'; | |
var visited = Date.now() + Math.random(); | |
var _current = [{}]; | |
var _keys = [[name || 'your_object']]; | |
var _index = [0]; | |
var results = []; | |
var current = obj; | |
var keys = Object.keys(obj) | |
var index = 0; | |
var value; | |
function iterate() { | |
index++; | |
// remove finished levels | |
while (keys && index >= keys.length) { | |
current = _current.pop(); | |
keys = _keys.pop(); | |
index = _index.pop() + 1; | |
} | |
} | |
//var count = 0; | |
while (_current.length) { | |
//count++; | |
//if (count % 1000000 === 0) | |
// console.log(count / 1000000); | |
//if (count > 10000000) | |
// return 'overflow :('; | |
value = current[keys[index]]; | |
if (value == null || value instanceof Element || value[key] === visited) { | |
iterate(); | |
continue; | |
} | |
value[key] = visited; | |
if ((value+'').indexOf(term) !== -1) { | |
results.push(_keys.reduceRight(function(path, keys, i) { | |
return keys[_index[i]] + '.' + path; | |
}, keys[index])); | |
iterate(); | |
continue; | |
} | |
if (typeof value !== 'object') { | |
iterate(); | |
continue; | |
} | |
_current.push(current); | |
_keys.push(keys); | |
_index.push(index); | |
current = value; | |
keys = Object.keys(value); | |
index = 0; | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment