Last active
May 14, 2018 07:32
-
-
Save futurist/66291cfdd63d0e951ff4f735957c4d2c to your computer and use it in GitHub Desktop.
Some collection of functional js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const curry = f => a => b => f(a, b) | |
const uncurry = f => (a, b) => f(a)(b) | |
const papply = (f, a) => b => f(a, b) | |
const compose2 = (f, g) => (...args) => f(g(...args)) | |
const compose = (...fns) => fns.reduce(compose2) | |
const pipe = (...fns) => fns.reduceRight(compose2) | |
// express.js like middle ware | |
// arg => fns[0](arg,null)->ret0 => fns[1](arg,ret0)->ret1 ... | |
const pipe2 = (fns, arg) => fns.reduce((p,c) => c(arg, p), null) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var add1 = x=>x+1 | |
var mul2 = x=>x*2 | |
function currying (func, ...args) { | |
return func.bind(null, ...args) | |
} | |
// https://hackernoon.com/currying-in-js-d9ddc64f162e | |
function curry(fn) { | |
if (fn.length === 0) { | |
return fn | |
} | |
function nest(N, args) { | |
return (x) => { | |
if (N - 1 === 0) { | |
return fn(...args, x) | |
} | |
return nest(N - 1, [...args, x]) | |
} | |
} | |
return nest(fn.length, []) | |
} | |
function compose2 () { | |
var funcs = arguments | |
return function () { | |
var args = arguments | |
var self = this | |
for (var i = 0; i < funcs.length; i++) { | |
args = [funcs[i].apply(self, args)] | |
} | |
return args[0] | |
} | |
} | |
// console.log(compose2(add1, mul2)(3)) | |
function compose (funcs) { | |
return function () { | |
var args = arguments | |
var self = this | |
for (var i = 0; i < funcs.length; i++) { | |
args = [funcs[i].apply(self, args)] | |
} | |
return args[0] | |
} | |
} | |
// console.log(compose([add1, mul2])(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment