ushumpei’s blog

生活で気になったことを随時調べて書いていきます。

JavaScript...

ES6から、「Spread operater」というものが追加されました。「...」を記述することで、配列やオブジェクトを展開する事ができる演算子だそうです。 例えば、

var [x, ...xs] = [1,2,3,4,5,6,7,8,9];
console.log(x);
//=> 1
console.log(xs);
//=> [2, 3, 4, 5, 6, 7, 8, 9]

分割代入との合わせ技だと思いますが、このように余った部分を配列で受け取ってくれます。

可変長引数等で使えますね。

サンプルコードを書いてみました。 比較方法が数値しか対応していなくて残念ですが、比較の優先順位を可変長で受け取るソート関数を書いてみました。

function mySort(array, ...properties) {
  if(properties.length <= 0) return array;
  let comp = (a, b) => {
    let res = 0;
    for(i = 0; i < properties.length; i++){
      let property = properties[i];
      if(match = /^-(.*)$/g.exec(property)) property = match[1];
      let sign = (match) ? -1 : 1;
      if(!(property in a)) throw new Error(`There is no property named ${property}`);
      res = sign * (a[property] - b[property]);
      if(res !== 0) break;
    }
    return res;
  }
  return [...array].sort(comp);
}
var objs = [
{id: 0, a:1, b:1, c:1, d:1},
{id: 1, a:1, b:1, c:1, d:2},
{id: 2, a:1, b:1, c:2, d:1},
{id: 3, a:1, b:1, c:2, d:2},
{id: 4, a:1, b:2, c:1, d:1},
{id: 5, a:1, b:2, c:1, d:2},
{id: 6, a:1, b:2, c:2, d:1},
{id: 7, a:1, b:2, c:2, d:2},
{id: 8, a:2, b:1, c:1, d:1},
{id: 9, a:2, b:1, c:1, d:2},
{id:10, a:2, b:1, c:2, d:1},
{id:11, a:2, b:1, c:2, d:2},
{id:12, a:2, b:2, c:1, d:1},
{id:13, a:2, b:2, c:1, d:2},
{id:14, a:2, b:2, c:2, d:1},
{id:15, a:2, b:2, c:2, d:2}
];
console.table( mySort(objs, '-a', 'b','c') );

配列への要素の追加も副作用なく簡単にかけます。

function mutableExclamate(list) {
  list.push('!');
  return list;
}

function immutableExclamate(list) {
  return [...list, '!'];
}

args = ['y','a','y'];
console.log(args);
//=> ["y", "a", "y"]
console.log(mutableExclamate(args));
//=> ["y", "a", "y", "!"]
console.log(args);
//=> ["y", "a", "y", "!"]

args = ['y','a','y'];
console.log(args);
//=> ["y", "a", "y"]
console.log(immutableExclamate(args));
//=> ["y", "a", "y", "!"]
console.log(args);
//=> ["y", "a", "y"]

そんなに想像力が働かないですね。 ただArray.prototypeを触らなければならない場面は減ると思います。