Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Last active July 21, 2016 21:34
Show Gist options
  • Save khaled0fares/964bebbd5216cc723d6ef35cdae5289d to your computer and use it in GitHub Desktop.
Save khaled0fares/964bebbd5216cc723d6ef35cdae5289d to your computer and use it in GitHub Desktop.
Reimplementation for unshift in JS
let deepCopy = function(copied, copy){
let i = 0, len = copy.length;
for(i; i < len; i++){
copied[i] = copy[i]
}
return copied;
}
Array.prototype.unShift = function (){
let newArray = [...arguments], i = 0, len = this.length, newArrLen = newArray.length;
for(i; i < len; i++,newArrLen++){
newArray[newArrLen] = this[i];
}
deepCopy(this, newArray);
}
//Another unshift implementation without deep copy
Array.prototype.unShift = function (first){
let len = this.length, i = len;
for(i; i > 0; i--){
this[i] = this[i - 1];
}
this[0] = first;
}
let arr =[1,2];
arr.unShift(3);
arr // [3,1,2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment