Last active
August 28, 2019 15:27
-
-
Save luc4leone/c602289f252ac6a4ca3a15e6d7e11964 to your computer and use it in GitHub Desktop.
A commented and edited version of Jake Ryan `copyWithin` version of the native js method
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
// jake you forgot the end parameter, added! | |
function copyWithin(originalArray, target, start, end) { | |
var originalLength = originalArray.length; | |
var elementsToCopy = []; | |
// the vars I need to break down the problem | |
var copyFrom, copyTo, pasteFrom, pasteTo; | |
// set copyFrom | |
// if undefined let's set it to 0 | |
if (!start) { | |
start = 0; | |
} | |
// set copyFrom to start, meaning 0 or a defined value | |
copyFrom = start; | |
// if this value is negative let's start counting from the end | |
if (copyFrom < 0) { | |
copyFrom += originalLength; | |
} | |
// set copyTo | |
var copyTo = end || originalLength; | |
if (copyTo < 0) { | |
copyTo += originalLength; | |
} | |
// get elementsToCopy | |
for (var i = copyFrom, k = 0; i < copyTo; i++) { | |
elementsToCopy[k] = originalArray[i]; | |
k++; | |
} | |
// set pasteFrom | |
// I commented out your calculation because it gave me problems if target < - originalLength | |
// if (target < 0) { | |
// target = target + originalLength; | |
// if (target < 0) { | |
// return originalArray; | |
// } | |
// } | |
pasteFrom = target; | |
if (pasteFrom < - originalLength) { | |
pasteFrom = 0; | |
} | |
if (pasteFrom < 0) { | |
pasteFrom += originalLength; | |
} | |
// set pasteTo | |
pasteTo = Math.min(pasteFrom + elementsToCopy.length, originalLength); | |
// paste elementsToCopy | |
for (var i = pasteFrom, k = 0; i < pasteTo; i++) { | |
originalArray[i] = elementsToCopy[k]; | |
k++; | |
} | |
return originalArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment