LoginSignup
8
7

More than 5 years have passed since last update.

JavaScriptの可変長引数を扱いやすく

Last updated at Posted at 2013-05-11
_.optarg = function (n, f) {
    return function (/* & arguments  */) {
        var required = Array.prototype.slice.call(arguments, 0, n);
        var optional = Array.prototype.slice.call(arguments, n);
        required.push(optional);
        return _.apply(f, required);
    };
};

これで

var f = function () {
  var a = arguments[0];
  var b = arguments[1];
  var rest = Array.prototype.slice.call(arguments, 2);
  //...
};

みたいなコードを

var g = _.optarg(2, function (a, b, rest) {
  //...
});

みたいに書ける。

_.bin_multi = function (binary_f) {
    return _.optarg(2, function (x, y, zs) {
        return _.foldl(zs, function (acc, a) {
            return binary_f(acc, a);
        }, binary_f(x, y));
    });
};

これで、

var add = _.bin_multi(function (a, b) {
  return a + b;
});

add(1,2,3,4,5,6,7,8,9,10); //=>55

みたいなことができる.

8
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
8
7