Skip to content

Instantly share code, notes, and snippets.

@donpayne
Last active July 10, 2017 17:34
Show Gist options
  • Save donpayne/95cb061fffe891645fc25c17d765d308 to your computer and use it in GitHub Desktop.
Save donpayne/95cb061fffe891645fc25c17d765d308 to your computer and use it in GitHub Desktop.
RecursiveCallList - Synchronous function queue caller until a valid value is returned (i.e., truthy or non-error)
// var _ = require('lodash');
var list = [
function eenie () { throw new Error('hey'); },
function meenie () { return 0; },
function minie () { return false; },
function moe () { return 'hello'; },
function catcha () { return 'world'; }
];
// Recurse a list of functions, calling them in order until a valid value is returned
function recursiveCallList (list) {
if (!isValid(list))
return;
return callFunc(_.first(list)) || recursiveCallList(_.tail(list));
}
// Validate input for the function list
function isValid (list) {
return _.overEvery([
_.isArray,
_.negate(_.isEmpty),
_.partial(_.every, _, _.isFunction)
])(list);
}
// Call a function and return value (catching errors)
function callFunc (func) {
var result = _.attempt(func);
return !_.isError(result) && result;
}
console.log(recursiveCallList(list));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment