Skip to content

Instantly share code, notes, and snippets.

@dszakallas
Last active February 1, 2018 20:35
Show Gist options
  • Save dszakallas/5a385682742fc9bc2cf4cbb6ce33b8c7 to your computer and use it in GitHub Desktop.
Save dszakallas/5a385682742fc9bc2cf4cbb6ce33b8c7 to your computer and use it in GitHub Desktop.
Javascript Snippets
// Turn a generator function into a coroutine
const coroutine = (f) => (...args) => {
const g = f(...args) // instantiate the generator
const iter = ({ done, value }) => done // iterate over suspensions
? value
: value.then(
(d) => iter(g.next(d)),
(e) => iter(g.throw(e))
)
return Promise.resolve().then(() => iter(g.next())) // start iterating asynchronously
}
// Curry a function
const curry = (f) => f.length
? (a) => curry(f.bind(null, a))
: f
const uncurry = (f) => (...args) => args.length
? uncurry(f(args[0]))(...args.slice(1))
: f()
// Turn a Node.js style continuation function into a promise
const promisify = (f) => (...args) =>
new Promise((resolve, reject) => f(...args, (err, d) => err != null ? reject(err) : resolve(d)))
// Turn a promise into a function that can be called with a Node.js style continuation function
const nodify = (p) => (cb) => p.then((d) => cb(null, d), cb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment