7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

演算子を関数にする関数

Posted at

うう、日本語がややこしい。

JavaScriptを関数型的に使いたい時に結構役に立つ。ついでにカリー化。

op2fn.js
function curry (fn) {
  return function curried() {
    var
    args = Array.prototype.slice.call(arguments, 0);
    return args.length >= fn.length ? fn.apply(this, arguments)
      : function () {
        return curried.apply(this, args.concat(Array.prototype.slice.apply(arguments)));
      };
  };
}
function op(o) {
  return curry(Function('x, y', 'return x ' + o + 'y;'));
}

使い方。

op2js-usage.js
var
xs = [1,2,3,4,5];

console.log(xs.reduce(op('*'))); //=> 120
console.log(xs.map(op('+')(10))); //=> [11,12,13,14,15]

カリー化されてるからmapにも渡せる。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?