Created
January 7, 2015 23:00
-
-
Save shawndumas/22f67c4442d0c36e9657 to your computer and use it in GitHub Desktop.
findNodesBy.js
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
/* 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