Open EdwardZZZ opened 5 years ago
const Type = (obj) => Object.prototype.toString.call(obj).slice(8, -1);
const complexType = (type) => ['Array', 'Object'].includes(type);
const CloneDeep = (value) => {
if (!complexType(Type(value))) return value;
const result = Array.isArray(value) ? [] : {};
// const task = [[value, result]]; // [source, dest][]
const task = [value, result];
const ref = new Set();
while (task.length) {
// const [source, dest] = task.shift();
const [source, dest] = task.splice(0, 2);
for (const k in source) {
if (!source.hasOwnProperty(k)) continue;
const desc = Reflect.getOwnPropertyDescriptor(source, k);
const { value: v, get, set } = desc;
if (get || set || !complexType(Type(v))) {
Reflect.defineProperty(dest, k, desc);
} else {
if (ref.has(v)) {
dest[k] = v;
} else {
dest[k] = Array.isArray(v) ? [] : {};
task.push(v, dest[k]);
}
}
}
ref.add(source);
}
return result;
};