node.js でライブラリを使わずに関数型する
node.js で関数型したい時には Ramda などの ライブラリを入れるのが一般的だと思いますが、 ちょっとしたツールを書く時には Ramda 入れるのも大げさに思える時があります。
で、よくよく調べてみると、map, filter, reduce はあるし、 部分適用も Function.prototype.bind() を使えばよさそう。
あとはカリー化と関数合成ができればいいんだけど、 関数合成については reduce を使えばいける事に気付いて こんな感じで定義してみました。
const pipe = (...fns) => val => fns.reduce((acc, fn) => fn(acc), val); const compose = (...fns) => val => fns.reduceRight((acc, fn) => fn(acc), val); const bind = (fn, ...args) => fn.bind(null, ...args);
こんな感じで使えます。
const add = (a, b) => a + b; const mul = (a, b) => a * b; const add1 = bind(add, 1); const mul2 = bind(mul, 2); let ret = 0; ret = pipe( add1, mul2 )(2); console.log(ret); // -> 6 ret = compose( add1, mul2 )(2); console.log(ret); // -> 5
カリー化はいい方法が見つかってないですが、 必要な場合は手動でやってます。
const addCurried = a => b => a + b; const add10 = addCurried(10); ret = add10(1) console.log(ret); // -> 11