Created
November 8, 2017 03:52
-
-
Save lsongdev/a45143923ad38f685fc051c41d74e2ea to your computer and use it in GitHub Desktop.
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
const clone = obj => { | |
const typeOf = o => | |
({}).toString.call(o).match(/\[object (\w+)\]/)[1]; | |
if(typeOf(obj) !== 'Object') | |
throw new TypeError('must be an object'); | |
var out = {}; | |
for(let attr in obj){ | |
const item = obj[attr]; | |
switch(typeOf(item)){ | |
case 'Number': | |
case 'String': | |
out[attr] = item; | |
break; | |
case 'Function': | |
out[attr] = item.bind(null); | |
break; | |
case 'Array': | |
out[attr] = item.map(x => x) | |
break; | |
case 'Object': | |
out[attr] = clone(item); | |
break; | |
} | |
} | |
return out; | |
}; | |
const obj = { | |
a: 1, | |
b: 2, | |
str: 'hello', | |
arr: [1,3,4,6,,7], | |
fn: (a, b) => a + b | |
} | |
const newOne = clone(obj); | |
console.log(newOne, newOne === obj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment