Skip to content

Instantly share code, notes, and snippets.

@alucky0707
Created April 10, 2013 11:36
Show Gist options
  • Save alucky0707/5353874 to your computer and use it in GitHub Desktop.
Save alucky0707/5353874 to your computer and use it in GitHub Desktop.
JavaScriptでRubyのように配列をスライスする ref: http://qiita.com/items/de269eddf2b359c3f490
var
arr = [0,1,2,3,4,5,6,7,8,9], //元となる配列
sli = toSlicer(arr); //配列を拡張
// 範囲代入と取得
sli["1..3"] = [10,11,12];
console.log(sli["0..2"]); //=>0,10,11
//複数代入と取得
sli["4,6,8"] = [13,14,15];
console.log(sli["4,5,7,9"]); //=>13,5,7,9
//Arrayのメソッドやプロパティ―ももちろん呼べる
sli.push(16);
console.log(sli.length); //=>11
//元となった配列を破壊的に参照してたりする
console.log(arr); //=> 0,10,11,12,13,5,14,7,15,9,16
// 配列のスワップ
sli["1,2"] = sli["2,1"];
var
i = 1,j = 2;
sli[[i,j]] = sli[[j,i]];
/**
* Slicerを使った破壊的なバブルソート
* @param {Array} ソートする配列
*/
function bubbleSort(arr) {
var
sli = toSlicer(arr),
i,j,len = sli.length;
for(i = 0; i < len; i++) {
for(j = len-1; j >= 0; j--) {
if(sli[j] < sli[i]){
//スワップ
sli[[i,j]] = sli[[j,i]];
}
}
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment