invoke() 各要素にメソッドを適用する
<script>
Array.prototype._each = function(iterator){
for(var i=0, l=this.length; i<l; i++){
iterator(this[i]);
}
};
Array.prototype.each = function(iterator){
var index = 0;
try{
this._each(function(v){
iterator(v, index++);
});
} catch(e){
if(e != $break) throw e;
}
};
Array.prototype.collect = function(iterator){
var iterator = iterator || function(x){return x};
var rs = [];
this.each(function(v, k){
rs.push(iterator(v, k));
});
return rs;
};
Array.prototype.invoke = function(method){
var args = $A(arguments).slice(1);
return this.collect(function(v, k){
return v[method].apply(v, args);
});
}
function $A(iterable){
if(!iterable) return [];
if(iterable.collect) return iterable.collect();
var length = iterable.length, rs = new Array(length);
while(length--) rs[length] = iterable[length];
return rs;
}
var $break = {};
var kekka = "hoge,moge,dada,yonsama".split(',').invoke('toUpperCase');
console.log(kekka);
var kekka = "hoge,moge,dada,yonsama".split(',').invoke('substring', 0, 2);
console.log(kekka);
var test = 'hoge';
console.log(test.toUpperCase.apply(test));
console.log(test.substring.apply(test, [0,2]));
</script>