Skip to content

Instantly share code, notes, and snippets.

@lukeasrodgers
Last active December 14, 2015 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukeasrodgers/5124636 to your computer and use it in GitHub Desktop.
Save lukeasrodgers/5124636 to your computer and use it in GitHub Desktop.
recursive deep detection in javascript with underscore and try/catch statements, inspired by ruby's throw/catch. jsperfs http://jsperf.com/deep-detect and http://jsperf.com/deep-detect-last-success
var deepDetect = function(list, iterator, context) {
var _deepDetect = function(list, iterator, context) {
if (_.isArray(list[0])) {
_.each(list, function(sublist) {
return _deepDetect(sublist, iterator, context);
});
}
else {
var res = _.detect(list, iterator, context);
if (!_.isUndefined(res)) {
throw res;
}
}
};
try {
_deepDetect(list, iterator, context);
}
catch (err) {
return err;
}
};
_.mixin({
deepDetect: deepDetect
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment