Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Created January 7, 2015 23:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawndumas/22f67c4442d0c36e9657 to your computer and use it in GitHub Desktop.
Save shawndumas/22f67c4442d0c36e9657 to your computer and use it in GitHub Desktop.
findNodesBy.js
/* globals module */
'using strict';
module.exports = function (options) {
if (arguments.length === 2) {
options = {
body: arguments[0],
match: arguments[1]
};
}
options.by = options.by || 'type';
options.visitor = options.visitor || function (k, v, p, a) { return v; };
var nodes = [],
isMatch = (function () {
var which = {
'[object String]': function (k, v) { return v === options.match; },
'[object RegExp]': function (k, v) { return options.match.test(v); },
'[object Function]': function (k, v, p, a) { return options.match(k, v, p, a); },
},
kind = ({}).toString.call(options.match);
return which[kind];
}());
JSON.stringify(
options.body,
function (key, value) {
var node;
if (value && value[options.by] && isMatch(key, value[options.by], this, nodes)) {
node = options.visitor(key, value, this, nodes);
if (node) {
nodes.push(node);
}
}
return value;
}
);
return nodes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment