JavascriptのArrayでeach,map,eachWithObject
Javascriptを触る機会があったのでちょっと試してみた。郷に入っては郷に従えというけれどJavascriptの流儀やAPIがわからなかったので、とりあえずArrayにeachとmap、eachWithObjectをくっつけてみた。
// [1,2,3].eachWithIndex(function(n,i) { console.log("#" + i + " = " + n)})
Array.prototype.eachWithIndex = function(func) {
var length = this.length;
for (var i = 0; i < length; i++) {
func.apply(this, [this[i], i]);
}
return this;
}
// [1,2,3].each(function(n) { console.log(n) })
Array.prototype.each = function(func) {
return this.eachWithIndex(function(x,i) {
func.apply(this, [x]);
})
}
// [1,2,3].map(function(n) { return n * 2; });
Array.prototype.map = function(func) {
var result = new Array();
this.eachWithIndex(function(x,i) {
result.push(func.apply(this, [x]));
});
return result;
}
// [1,2,3].eachWithObject({}, function(s, n) { s[n.toString] = n * 100 });
Array.prototype.eachWithObject = function(obj, func) {
this.eachWithIndex(function(x,i) {
func.apply(this, [obj, x]);
});
return obj;
}
func.applyは関数オブジェクトfuncの処理を走らせるもので、Proc#callみたいなもの。第1引数にはfunc内でthisが参照するオブジェクトを、第2引数にはfuncの引数を配列で与えてやる。
引数は参照渡しされる。
JavascriptのリファレンスはMozillaのとこが詳しい。ただしJavascriptの実行エンジンの種類やバージョンで差異があるので要注意。ここらへんの一覧ってないのかな?
Javascriptはオブジェクト指向言語のなかでもプロトタイプベース(もしくはインスタンスベース)と呼ばれるものに区分されるらしい。間違ってるだろうけど、インスタンスにメソッドを生やして行くような感覚がある。