2022-11-16 17:31:07 -07:00
|
|
|
// structredCloneが遅いため
|
|
|
|
// SEE: http://var.blog.jp/archives/86038606.html
|
|
|
|
|
2023-01-12 21:40:33 -07:00
|
|
|
type Cloneable =
|
|
|
|
| string
|
|
|
|
| number
|
|
|
|
| boolean
|
|
|
|
| null
|
|
|
|
| { [key: string]: Cloneable }
|
|
|
|
| Cloneable[];
|
2022-11-16 17:31:07 -07:00
|
|
|
|
|
|
|
export function deepClone<T extends Cloneable>(x: T): T {
|
2023-01-12 21:40:33 -07:00
|
|
|
if (typeof x === "object") {
|
2022-11-16 17:31:07 -07:00
|
|
|
if (x === null) return x;
|
|
|
|
if (Array.isArray(x)) return x.map(deepClone) as T;
|
|
|
|
const obj = {} as Record<string, Cloneable>;
|
|
|
|
for (const [k, v] of Object.entries(x)) {
|
|
|
|
obj[k] = deepClone(v);
|
|
|
|
}
|
|
|
|
return obj as T;
|
|
|
|
} else {
|
|
|
|
return x;
|
|
|
|
}
|
|
|
|
}
|