配列を回転する

条件

  • 参照元の配列を破壊しないこと。
  • 1行で済ませること。
  • 身勝手ではあるがなるべく reverse は使わないこと。
  • なるべく速度を優先すること。(調べていないけど)
const ary = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [10,11,12]
];

const tb = a=> a.map (b=>b.join (', ')).join ('\n');


//転置(XとYを交換)
const transpose=a=>a[0].map((_,i)=>a.map(b=>b[i]));

//回転(時計回り)
//const rotate=Right a=> a[0].map((_,i)=>a.map(b=>b[i]).reverse());
const rotateRight = a=> a[0].map((_,i)=>a.reduceRight((b,c)=>[...b,c[i]],[]));

//回転(180度)
//const inversion =a=> [...a].reverse().map(b=>[...b].reverse());
//const inversion =a=> a.slice().reverse().map(b=>b.slice().reverse());
//const inversion =a=> a.reduceRight((b,c)=>[...b,[...c].reverse()],[]);
const inversion = a=>a.reduceRight((b,c)=>[...b,c.reduceRight((d,e)=>[...d,e],[])],[]);

//回転(反時計回り)
const rotateLeft = a=> a[0].reduceRight((b,_,i)=>[...b,a.map(c=>c[i])],[]);



//_____________
let A = ary;
console.log (tb (A));
console.log (tb (rotateRight (rotateRight (A))));
console.log (tb (inversion (A)));
console.log (tb (rotateLeft (rotateLeft (A))));

/*
[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [10, 11, 12],
]

[
  [12, 11, 10],
  [9, 8, 7],
  [6, 5, 4],
  [3, 2, 1],
]

*/