DEV Community

Discussion on: Not an "Easy" Algorithm: Rotating an Array, Three Ways

Collapse
 
realdolos profile image
Dolores Greatamsky

Quick and really dirty and not exactly efficient :D

function rrotate(arr, steps) {
  steps = (steps || 0) % arr.length;
  return new Proxy(arr, {
    get(target, prop) {
      const idx = typeof prop === "string" ? Number(prop) - steps : NaN;
      return Number.isInteger(idx) ?
         target[idx >= 0 ? idx : target.length + idx] :
         target[prop];
    }
   });
}

But it works (mostly)

Array.from(rrotate([1,2,3,4,5], 2))
// [4, 5, 1, 2, 3]
rrotate([1,2,3,4,5], 2).slice()
// [4, 5, 1, 2, 3]
rrotate([1,2,3,4,5], 2).forEach(e => console.log(e))
// 4
// 5
// 1
// 2
// 3
[...rrotate([1,2,3,4,5], 7)]
// [4, 5, 1, 2, 3]
for (let e of rrotate([1,2,3,4,5], 12)) console.log(e);
// 4
// 5
// 1
// 2
// 3