Skip to content

Instantly share code, notes, and snippets.

@pfgray
Created August 2, 2018 05:05
Show Gist options
  • Select an option

  • Save pfgray/f8f39eb293037783a05dbf39ea548829 to your computer and use it in GitHub Desktop.

Select an option

Save pfgray/f8f39eb293037783a05dbf39ea548829 to your computer and use it in GitHub Desktop.
Do syntax for js
// nested chaining is a common occurence for monads:
// type Maybe = Just(a) | Nothing
Just(5)
.chain(num => Just(num * 2)
.chain(num2 => Just(num2 + 3)
.map(num3 => ({num, num2, num3}))
)
)
// this yields:
// Just({
// num: 5,
// num2: 10,
// num3: 13
// })
// To avoid nesting, we can implement a function Do, which takes
// instances of Monads, and an arbitrary list of functions with
// increasing parameter count, and chains them automatically:
Do(
Just(5),
(num) => Just(num * 2),
(num, num2) => Just(num2 + 3),
(num, num2, num3) => ({num, num2, num3})
)
// which yields:
// Just({
// num: 5,
// num2: 10,
// num3: 13
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment