-
-
Save AliceWonderland/ae6492386c2136211f124d5e9c120d19 to your computer and use it in GitHub Desktop.
8.4 Deeper Copy created by smillaraaq - https://repl.it/HJll/15
This file contains hidden or 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
//slice() does a pass by reference not value if the value it's passing is an object! | |
function copy(ary){ | |
//loop thru ary check typeof | |
//if object loop through, copy each value individually | |
var resultArray=[]; | |
for(var i=0;i<ary.length;i++){ | |
var tmpItem=copyIndefinite(ary[i]); | |
// console.log(tmpItem); | |
resultArray.push(tmpItem); | |
} | |
// console.log("sd ",resultArray) | |
return resultArray; | |
} | |
var arr = [1,[2,3]]; | |
var arrCopy = copy(arr); | |
arr[1].push(4); | |
console.log("ww",arrCopy) // [1,[2,3]] Copy is not affected! | |
//bonus recursion | |
function copyIndefinite(item){ | |
//loop thru ary check typeof | |
//if object loop through, copy each value individually | |
var result=0; | |
var tmpItem=0; | |
if(Array.isArray(item)){//check if isArray | |
var tmpAry=[]; | |
for(var x=0;x<item.length;x++){ | |
tmpAry.push(item[x]); | |
} | |
tmpItem=tmpAry; | |
}else if(typeof item==="object"){//check if any other type of object | |
//push key values | |
tmpItem="some obj"; | |
}else{ | |
//primitive data type | |
tmpItem=item; | |
} | |
result=tmpItem; | |
// console.log("sd ",resultArray) | |
return result; | |
} | |
/* SCHOOL SOLUTION | |
function copy (arr) { | |
var copyArr = []; | |
for (var i=0; i<arr.length; i++) { | |
if (Array.isArray(arr[i])) { | |
var nestedCopy = []; | |
for (var j=0; j<arr[i].length; j++) { | |
nestedCopy.push(arr[i][j]); | |
} | |
copyArr.push(nestedCopy) | |
} else { | |
copyArr.push(arr[i]); | |
} | |
} | |
return copyArr; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment