Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created August 30, 2011 04:04
Show Gist options
  • Save ishiduca/1180157 to your computer and use it in GitHub Desktop.
Save ishiduca/1180157 to your computer and use it in GitHub Desktop.
任意の数値を保持した状態で、別の数値を加える方法
var f1, // カリー化っぽく
f2, // new 演算子を使ってオブジェクトを作る
f3, // オブジェクトを返す関数を作って
f4; // Number.prototypeを使う
f1 = function () {
var add = function (a) {
return function (b) {
return _add(a, b);
};
};
var n = add(1);
test(n(2), 3);
};
f2 = function () {
var add = function (a) {
this.a = a;
this.add = function (b) {
return _add(this.a, b);
};
};
var n = new add (3);
test(n.add(4), 7);
};
f3 = function () {
var add = function (a) {
return {
add : function (b) {
return _add(a, b);
}
};
};
var n = add(5);
test(n.add(6), 11);
};
f4 = function () {
if (! Number.prototype.add) {
Number.prototype.add = function (b) {
return _add(this,b);
};
var n = 7;
test(n.add(8), 15);
}
};
f1();
f2();
f3();
f4();
test((9).add(10), 19);
/* Functions */
function test (result, forecast) {
var is_success = (result === forecast) ? 'success:' : '! failed:';
console.log([is_success, result, forecast].join(' '));
}
function toNumber (n) {
return (typeof n === 'number') ? n
: (Number(n)) ? Number(n)
: 0;
}
function _add (a, b) {
return toNumber(a) + toNumber(b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment