summaryrefslogtreecommitdiff
path: root/packages/frontend/src/scripts/clone.ts
blob: 16fad2412943a8cd30abfdfa0091e5e8e66919f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// structredCloneが遅いため
// SEE: http://var.blog.jp/archives/86038606.html

type Cloneable = string | number | boolean | null | { [key: string]: Cloneable } | Cloneable[];

export function deepClone<T extends Cloneable>(x: T): T {
	if (typeof x === 'object') {
		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;
	}
}