Skip to content

Instantly share code, notes, and snippets.

@honzabrecka
Last active May 11, 2016 13:07
Show Gist options
  • Save honzabrecka/9a7a797cdb1bb03e63022022d3bdef4d to your computer and use it in GitHub Desktop.
Save honzabrecka/9a7a797cdb1bb03e63022022d3bdef4d to your computer and use it in GitHub Desktop.
const data = {
a: {
b: {
c: 10
}
}
}
const pipe = (fs) => (v) => fs.reduce((acc, f) => f(acc), v)
const tap = (f) => (v) => {
f(v)
return v
}
const log = tap((v) => console.log('>>>', v))
const get = (key) => (data) => data[key] ? data[key] : null
console.log(
pipe([
get('a'),
get('b'),
get('c')
])(data)
)
let bind = (v, f) => !v ? null : f(v)
let result = (v) => v
console.log(
bind(get(log('a'))(data), (a) =>
bind(get(log('b'))(a), (b) =>
bind(get(log('c'))(b), (c) =>
result(c))))
)
const sum = (a, b, c) => a + b + c
console.log(
bind(null, (a) =>
bind(2, (b) =>
bind(3, (c) =>
result(sum(a, b, c)))))
)
const maybeM = {
unit: (v) => [v],
bind: ([v], f) => !v ? [null] : [f(v)]
}
const writerM = (s = []) => ({
unit: (v) => [s, v],
bind: ([s, v], f) => {
const [w, nv] = f(v)
return [s.concat(w), nv]
}
})
const w = (f, m) => (v) => [m, f(v)]
const doM = ({unit, bind}, fs) => (data) => pipe(fs.map((f) => (v) => bind(v, f)))(unit(data))
console.log(
'doM:',
doM(maybeM, [get('a'), get('b'), get('c')])(data),
doM(writerM(), [w(get('a'), 'get a'), w(get('b'), 'get b'), w(get('c'), 'get c')])(data)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment