-
Notifications
You must be signed in to change notification settings - Fork 0
/
clone.ts
32 lines (30 loc) · 1.01 KB
/
clone.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export type JsonPrimitive = number | string | boolean | null;
export type JsonObject = JsonValue[] | { [key: string]: JsonValue };
export type JsonValue = JsonPrimitive | JsonObject;
/**
* Creates a deep clone of a JSON value.
*/
export function cloneJson<T extends JsonValue>(x: T): T {
return typeof x !== 'object' || x === null ? x : cloneJsonObject(x);
}
/**
* Creates a deep clone of a JSON object.
* Only array or object can be specified.
*/
export function cloneJsonObject<T extends JsonObject>(x: T): T {
if (Array.isArray(x)) {
const ret: JsonValue[] = Array(x.length);
let i = 0;
for (const e of x) {
ret[i++] = typeof e !== 'object' || e === null ? e : cloneJsonObject(e);
}
return ret as T;
} else {
const ret: { [key: string]: JsonValue } = {};
for (const k in x) {
const v = x[k] as JsonValue;
ret[k] = typeof v !== 'object' || v === null ? v : cloneJsonObject(v);
}
return ret as T;
}
}