Last active
March 31, 2017 01:21
-
-
Save Azerothian/ff058f9e135421fa04d7f6a406ed3c83 to your computer and use it in GitHub Desktop.
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
/// 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