Skip to content

Instantly share code, notes, and snippets.

Created April 18, 2017 07:28
Show Gist options
  • Save anonymous/fbf483307485c7c66f69ba35a031bbd9 to your computer and use it in GitHub Desktop.
Save anonymous/fbf483307485c7c66f69ba35a031bbd9 to your computer and use it in GitHub Desktop.
8.4 Deeper Copy created by smillaraaq - https://repl.it/HJll/15
//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