JavaScriptのArrayオブジェクトにmapメソッドとshuffleメソッドを実装する方法
当局の事情聴取に対し
等と供述していたことが判った。
ないなら実装してしまえ!
とりあえずjQueryで書いてみた
if( typeof Array.prototype.map === 'undefined') Array.prototype.map = function($_){ return jQuery.map(this,$_); }
jQuery.mapさん何してるの!?
chromeでnative版とjQuery版のベンチを取ってみたら倍ぐらい違ったのでjQueryを使わないで実装。
native版とほぼ変わらない実行速度になりました。
if( typeof Array.prototype.map === 'undefined') Array.prototype.map = function($callback){ var len = this.length; var $_ = new Array(len); for(var i =0; i<len; i++){ $_[i] = $callback.call(this,this[i],i); } return $_; };
Schwartzianで配列のシャッフルを実装
シンプルでいいですよね。(jQuery.map版は配列を返すとマージされてしまうので動きません。)
if( typeof Array.prototype.shuffle === 'undefined') Array.prototype.shuffle = function(){ return this .map(function($_){return [Math.random(),$_]}) .sort(function(a,b){return a[0] - b[0]}) .map(function($_){return $_[1]}) ; };
まとめ
array.extends.jsとか適当に名前付けて保存しとこう
/* (C) makoto@2ch.to */ if( typeof Array.prototype.map === 'undefined') Array.prototype.map = function($callback){ var len = this.length; var $_ = new Array(len); for(var i =0; i<len; i++){ $_[i] = $callback.call(this,this[i],i); } return $_; }; if( typeof Array.prototype.shuffle === 'undefined') Array.prototype.shuffle = function(){ return this .map(function($_){return [Math.random(),$_]}) .sort(function(a,b){return a[0] - b[0]}) .map(function($_){return $_[1]}) ; };