Rotate the elements in an array in JavaScript

后端 未结 30 1672
走了就别回头了
走了就别回头了 2020-11-22 10:55

I was wondering what was the most efficient way to rotate a JavaScript array.

I came up with this solution, where a positive n rotates the array to the

30条回答
  •  眼角桃花
    2020-11-22 11:03

    Type-safe, generic version which mutates the array:

    Array.prototype.rotate = (function() {
        // save references to array functions to make lookup faster
        var push = Array.prototype.push,
            splice = Array.prototype.splice;
    
        return function(count) {
            var len = this.length >>> 0, // convert to uint
                count = count >> 0; // convert to int
    
            // convert count to value in range [0, len)
            count = ((count % len) + len) % len;
    
            // use splice.call() instead of this.splice() to make function generic
            push.apply(this, splice.call(this, 0, count));
            return this;
        };
    })();
    

    In the comments, Jean raised the issue that the code doesn't support overloading of push() and splice(). I don't think this is really useful (see comments), but a quick solution (somewhat of a hack, though) would be to replace the line

    push.apply(this, splice.call(this, 0, count));
    

    with this one:

    (this.push || push).apply(this, (this.splice || splice).call(this, 0, count));
    

    Using unshift() instead of push() is nearly twice as fast in Opera 10, whereas the differences in FF were negligible; the code:

    Array.prototype.rotate = (function() {
        var unshift = Array.prototype.unshift,
            splice = Array.prototype.splice;
    
        return function(count) {
            var len = this.length >>> 0,
                count = count >> 0;
    
            unshift.apply(this, splice.call(this, count % len, len));
            return this;
        };
    })();
    

提交回复
热议问题