Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created November 16, 2011 09:23
Show Gist options
  • Save ishiduca/1369669 to your computer and use it in GitHub Desktop.
Save ishiduca/1369669 to your computer and use it in GitHub Desktop.
ラムダ(あとで消す)
if (! Array.prototype.filter) {
Array.prototype.filter = function (patternFunc) {
var helper = function (thisArray, newArray) {
if (! newArray) newArray = [];
if (thisArray && thisArray.length > 0) {
var el = thisArray.shift();
if (patternFunc(el)) newArray.push(el);
return helper(thisArray, newArray);
}
return newArray;
};
return helper(this.slice(0));
};
}
if (! Array.prototype.map) {
Array.prototype.map = function (patternFunc) {
var helper = function (thisArray, newArray) {
if (! newArray) newArray = [];
if (thisArray && thisArray.length > 0) {
var el = thisArray.shift();
return helper(thisArray, newArray.push(patternFunc(el)));
}
return newArray;
};
return helper(this.slice(0));
};
}
if (! Array.prototype.folded) {
Array.prototype.folded = function (func, i) {
var helper = function (arry) {
if (arry && arry.length > 0) {
i = func(i, arry.shift());
return helper(arry);
}
return i;
};
return helper(this.slice(0));
};
}
var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
var b = a.filter(function (i) {
return (i % 2 === 0) ? 1 : 0;
});
var c = a.map(function (i) {
return i * 2;
});
var d = a.folded(function (n1, n2) {
return n1 + n2;
}, 0);
var e = a.folded(function (n1, n2) {
return n1 * n2;
}, 1);
console.log(a);
console.log(b); // filter
console.log(c); // map
console.log(d); // fold: sum
console.log(e); // fold: prod
console.log(a);
console.log([ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ].folded(function (a, b) {
return a.concat(b);
}, []);
// [ 1, 2, 3, 4, 5, 6 ]
@ishiduca
Copy link
Author

配列(Array)のメソッド内部で使われてる helper 関数が使い捨て関数になってま。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment