Javascript Array rotate()

Description

Javascript Array rotate()


Array.prototype.rotate = function(){
  if(this.length === 0) {
    return this;//from w  w w .  ja v  a2  s . co  m
  }

  var item = this.shift();
  this.push(item);
  
  return this;
}

Array.prototype.first = function(){
  return this[0];
}

Javascript Array rotate()

Array.prototype.rotate = (function(){
 var unshift = Array.prototype.unshift,
 push=Array.prototype.push,
 splice=Array.prototype.splice;

 return function(count){
  var len=this.length >>>0,
  count = count >> 0;/*from w  w w.j av  a  2  s . c o  m*/
  count = count % len;
  
  push.apply(this,splice.call(this,count,len));
  
  return this;
 };
})();

var arr=[1,2,3,4,5];
arr.rotate(-2);
console.log(arr);

Javascript Array rotate()

/*/* w  ww  .  j  a v a2 s  . c om*/
 * Chapter 1
 * Page 91
 *
 * 1.7 Given an image represented by an NxN matrix,
 * where each pixel in the image is 4 bytes,
 * write a method to rotate the image by 90 degrees.
 * Can you do this in place?
 */

Array.prototype.rotate = function() {
  var newMatrix = [];
  const rowLength = Math.sqrt(this.length);
  newMatrix.length = this.length;

  for (var i = 0; i < this.length; i++) {
    const x = i % rowLength;
    const y = Math.floor(i / rowLength);

    const newX = rowLength - y - 1;
    const newY = x;

    const newPosition = newY * rowLength + newX;
    newMatrix[newPosition] = this[i];
  }

  return newMatrix;
}



PreviousNext

Related