Skip to content

Instantly share code, notes, and snippets.

@gblok
Created August 11, 2019 12:23
Show Gist options
  • Save gblok/ebd87b6a7e0d482dc218d96d4086f53c to your computer and use it in GitHub Desktop.
Save gblok/ebd87b6a7e0d482dc218d96d4086f53c to your computer and use it in GitHub Desktop.
js fn utils compose/pipe curry/uncarry
const compose = (...fns) => x => fns.reduceRight((g, f) => f(g), x)
const pipe = (...fns) => compose.apply(null, fns.reverse())
const composeAsync = (...fns) => x => fns.reduceRight((f, g) => f.then(g), Promise.resolve(x))
const pipeAsync = (...fns) => x => composeAsync.apply(null, fns.reverse())
const curry = (f, ...a) =>
a.length === f.length
? f(...a)
: curry.bind(null, f, ...a)
const uncurry = f => (...a) => {
const r = a.reduce((f, g) => f(g), f)
return r instanceof Function
? uncurry(r)
: r
}
const sum = (a, b, c, d) => a + b + c + d
const sum2 = a => b => c => d => a + b + c + d
const txc = compose(curry, uncurry)
const c = txc(sum2)
const y1 = c(1, 2, 3, 4)
const y2 = c(1, 2, 3)(4)
const y3 = c(1, 2)(3)(4)
const y4 = c(1)(2)(3)(4)
const y5 = c(1)(2, 3, 4)
const y6 = c(1)(2)(3, 4)
const y7 = c(1, 2)(3, 4)
const y8 = c(1, 2)(3, 4)
console.log({y1, y2, y3, y4, y5, y6, y7, y8})
const txp = pipe(curry, uncurry)
const p = txp(sum)
const z1 = p(1, 2, 3, 4)
const z2 = p(1, 2, 3)(4)
const z3 = p(1, 2)(3)(4)
const z4 = p(1)(2)(3)(4)
const z5 = p(1)(2, 3, 4)
const z6 = p(1)(2)(3, 4)
const z7 = p(1, 2)(3, 4)
const z8 = p(1, 2)(3, 4)
console.log({z1, z2, z3, z4, z5, z6, z7, z8})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment