Array.prototype.rotate

A built-in method for arrays that shifts the array's elements to the left or right, without changing the length of the array.

eg.

// shift left by two positions
let a = [1, 2, 3, 4, 5];
console.log(a.rotate(2)); // [1, 2]
console.log(a); // [3, 4, 5, 1, 2]
// shift right by two positions
// same as shifting left by minus two positions
let a = [1, 2, 3, 4, 5];
console.log(a.rotate(-2)); // [5, 4]
console.log(a); // [4, 5, 1, 2, 3]

A very low-effort way of doing these currently:

function rotateLeft(arr: any[], places: number): any[] {
    const res = new Array(places);
    for(let i = 0; i < places; ++i) {
        const item = arr.shift();
        arr.push(item);
        res[i] = item;
    }
    return res;
}

function rotateRight(arr: any[], places: number): any[] {
    const res = new Array(places);
    for(let i = 0; i < places; ++i) {
        const item = arr.pop();
        arr.unshift(item);
        res[i] = item;
    }
    return res;
}
2 Likes

What’s the use case? Why would we want to add more mutating methods to arrays? You can do this in a non-mutating way with % and an index, or with slice and concat.

1 Like

The use case is indeed niche.

The shift() method can be used in a queue. The rotate() method is just the same but for a circular queue.

It can also be used for cases like spinning a wheel of fortune or a revolver. In these cases, you want to rotate it n times from the starting point. The next rotation should start from the previous end point.

The method can be made to not mutate the target array using a slice(), like how a reversed version of an array can be obtained with target.slice().reverse().

2 Likes

If the use case is niche, and it's not difficult to do in userland, that seems like a pretty strong argument against adding it to the language?

2 Likes

For me, this is probably the best "defense" for these methods. But it can be "debunked" by an actual CircularBuffer data structure, which is specially optimized for that task. But JS doesn't have such class. The "circular queue argument" is in favor of rotational queues, not necessarily the methods proposed.

I agree with ljharb, it doesn't seem to be worth adding to the spec. We need more research to back it up, if we ever hope it'll get added

1 Like