Rotate the elements in an array in JavaScript

后端 未结 30 1573
走了就别回头了
走了就别回头了 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:04

    see http://jsperf.com/js-rotate-array/8

    function reverse(a, from, to) {
      --from;
      while (++from < --to) {
        var tmp = a[from];
        a[from] = a[to];
        a[to] = tmp;
      }
    }
    
    function rotate(a, from, to, k) {
      var n = to - from;
      k = (k % n + n) % n;
      if (k > 0) {
        reverse(a, from, from + k);
        reverse(a, from + k, to);
        reverse(a, from, to);
      }
    }
    

提交回复
热议问题