Skip to content

Instantly share code, notes, and snippets.

@nicolasparada
Last active September 25, 2016 02:59
Show Gist options
  • Save nicolasparada/8b7ef29abeec3dc8790723683299f34c to your computer and use it in GitHub Desktop.
Save nicolasparada/8b7ef29abeec3dc8790723683299f34c to your computer and use it in GitHub Desktop.
const waterfall = (array = []) => {
const iterate = index => (...args) => {
const fn = array[index]
const next = iterate(index + 1)
return fn ?
Promise.resolve(fn(...args, next)) :
Promise.resolve(...args)
}
try {
return iterate(0)()
} catch (ex) {
return Promise.reject(ex)
}
}
@nicolasparada
Copy link
Author

nicolasparada commented Sep 25, 2016

Usage:

const arr = []

arr.push(next => { // First one doen't have any other param than next
  return next({ foo: 'bar' })
})

arr.push((acc, next) => {
  acc.baz = 'qux'
  return next(acc)
})

arr.push((acc, next) => {
  acc.quux = 'corge'
  return next(acc)
})

waterfall(arr).then(console.log) // { foo: 'bar', baz: 'qux', quux: 'corge' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment