Skip to content

Instantly share code, notes, and snippets.

@Azerothian
Last active March 31, 2017 01:21
Show Gist options
  • Save Azerothian/ff058f9e135421fa04d7f6a406ed3c83 to your computer and use it in GitHub Desktop.
Save Azerothian/ff058f9e135421fa04d7f6a406ed3c83 to your computer and use it in GitHub Desktop.
/// synchronous processing of array data using promises
function waterfall(arr, func, initVar) {
return arr.reduce((promise, va) => {
return promise.then((prevVar) => {
const result = func(va);
if (isFunction(result)) {
return result(prevVar);
}
return result;
});
}, Promise.resolve(initVar));
}
function isFunction(functionToCheck) {
return functionToCheck && ({}).toString.call(functionToCheck) === "[object Function]";
}
waterfall([1,2,3,4,5], (val) => {
console.log(val);
});
// -- output --
// 1
// 2
// 3
// 4
// 5
waterfall([1,2,3,4,5], (val) => {
return (prev) => {
console.log(prev);
return prev + val;
}
}, 1);
// -- output --
// 1
// 2
// 4
// 7
// 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment