Skip to content

Instantly share code, notes, and snippets.

@wlib
Last active March 8, 2019 21:23
Show Gist options
  • Save wlib/1168801b68e291dbd2ef0814efe7e239 to your computer and use it in GitHub Desktop.
Save wlib/1168801b68e291dbd2ef0814efe7e239 to your computer and use it in GitHub Desktop.
Super simple Task implementation. Lazy evaluation of anything sequentially.
const Task = run => ({
// (a -> e) -> (a -> r) -> Task(a) // Might be inaccurate idk
run,
// undefined -> undefined
log: () =>
run(console.error)
(console.log),
// (a -> b) -> Task(b)
map: f =>
Task(err => res =>
run(err)
(x => res(f(x)) )),
// (a -> Task(b)) -> Task(b)
runMap: f =>
Task(err => res =>
run(err)
(x => f(x).run(err)
(res) ))
})
/* Sample Usage:
const http = (uri, method = "GET") =>
Task(err => res => {
const xhr = new XMLHttpRequest()
xhr.open(method, uri, true)
xhr.onload = () =>
(xhr.status < 300 && xhr.status >= 200)
? res(xhr.response)
: err(xhr.status + " " + xhr.statusText)
xhr.onerror = err
xhr.send()
})
app = http("https://randomuser.me/api")
.map(JSON.parse)
.map(x => x.results)
// Run it when you want
app.run(err => console.error(err))
(res => console.log(res))
// Shorthand for convenience
app.log()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment