Skip to content

Instantly share code, notes, and snippets.

@liady
Last active May 28, 2016 19:32
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 liady/0d9ec0c71f939c3789c601e2fcf282ef to your computer and use it in GitHub Desktop.
Save liady/0d9ec0c71f939c3789c601e2fcf282ef to your computer and use it in GitHub Desktop.
/**
* 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