javascript 同一オブジェクトのプロパティを比較する場合に匿名関数を使って短く書きたい

var a = {
  id   : 1,
  name : 'test1'
};

var b = {
  id   : 2,
  name : 'test2'
};
var compare = (x,y,i) => x + y*(-i||1);
[a,b].map( x => x.id ).reduce( compare,0 );
[a,b].map( x => x.name.startsWith('test') ).reduce( compare,0 );
[a,b].map( x => x.name.endsWith('2') ).reduce( compare,0 );
[a,b].map( x => x.name.endsWith('1') ).reduce( compare,0 );
  • プロトタイプ宣言するともっとすっきり
Array.prototype.compare = function(){
  return Math.sign(this.reduce( (x,y,i) => x + y*(-i||1),0 ))
}

[a,b].map( x => x.id ).compare();
[a,b].map( x => x.name.startsWith('test') ).compare()
[a,b].map( x => x.name.endsWith('2') ).compare()
[a,b].map( x => x.name.endsWith('1') ).compare()