Last active
July 21, 2016 21:34
-
-
Save khaled0fares/964bebbd5216cc723d6ef35cdae5289d to your computer and use it in GitHub Desktop.
Reimplementation for unshift in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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