amatiasq
12/12/2013 - 4:52 PM

Dirty code than recursively analyzes a object for a specific string without using recursive functions because of call stack limit.

Dirty code than recursively analyzes a object for a specific string without using recursive functions because of call stack limit.

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; 
}