Last active
May 28, 2016 19:32
-
-
Save liady/0d9ec0c71f939c3789c601e2fcf282ef to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* This solves the problem using Lodash's _.reduceRight, | |
* it runs backwards on the array, and makes each function/int to trigger the next ones | |
*/ | |
function sequence(list = []){ | |
_.reduceRight(list, (next, item) => () => _.isFunction(item) ? next(item()): setTimeout(next, item), () => {})(); | |
} | |
/** | |
* This solves it without using iteration, but tail recursion, | |
* it runs each item and then calls recursively on the rest. | |
* It brilliantly uses the setTimeout to either run the function, or delay with the int | |
*/ | |
function sequence([item = null, ...rest]){ | |
item && setTimeout(() => sequence(rest), _.isFunction(item) ? (item() , 0) : item); | |
} | |
/** | |
* Same as the previous solution (recursion, rest params & brilliance), | |
* but without running the functions themselves in setTimeout | |
*/ | |
function sequence([item = null, ...rest]){ | |
item && (_.isFunction(item) ? sequence(rest, item()) : setTimeout(() => sequence(rest), item)); | |
} | |
/** | |
* This solves it using the old fashioned map/reduce, | |
* where each item turns to a Promise, and the the promises are run sequentially. | |
*/ | |
function sequence(list = []) { | |
list | |
.map(item => () => new Promise(resolve => _.isFunction(item) ? resolve(item()) : setTimeout(resolve, item))) | |
.reduce((prev, next) => prev.then(next), Promise.resolve()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment