実行例#
/**
* オブジェクトをコピー
* @param obj 対象オブジェクト
* @return 新しいオブジェクト
*/
export const deepCopy = (obj) => {
if (Object(obj) !== obj) {
return obj;
}
if (obj instanceof Set) {
return new Set(obj);
}
if (obj instanceof Date) {
return new Date(obj);
}
if (typeof obj === 'function') {
return obj.bind({});
}
if (Array.isArray(obj)) {
const obj2 = [];
const len = obj.length;
for (let i = 0; i < len; i++) {
obj2.push(deepCopy(obj[i]));
}
return obj2;
}
const result = Object.create({});
let keys = Object.keys(obj);
if (obj instanceof Error) {
keys = Object.getOwnPropertyNames(obj);
}
const len = keys.length;
for (let i = 0; i < len; i++) {
const key = keys[i];
result[key] = deepCopy(obj[key]);
}
return result;
}