Skip to content

Instantly share code, notes, and snippets.

@lsongdev
Created November 8, 2017 03:52
Show Gist options
  • Save lsongdev/a45143923ad38f685fc051c41d74e2ea to your computer and use it in GitHub Desktop.
Save lsongdev/a45143923ad38f685fc051c41d74e2ea to your computer and use it in GitHub Desktop.
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