/
clone.ts
321 lines (285 loc) · 8.81 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { difference } from '../array/difference';
import { intersection } from '../array/intersection';
import { merge } from '../map/merge';
/**
* #### Cloning Options
* Cloning options of the [clone]{@link clone} function
*/
export interface ICloneOptions {
/**
* #### Instance constructors which cloning unwanted
* Give the instance constructors to prevent them being cloned
*
* * * *
* Example:
* ```typescript
* import { clone } from "@thalesrc/js-utils/object";
*
* const object = {
* width: 250,
* element: document.querySelector("div")
* };
*
* const clonedObject = clone(object, {instancesToRefer: [ HTMLElement ]});
* // clonedObject.element === object.element
* ```
* * * *
* @default []
*/
instancesToRefer?: any[];
/**
* #### Value filterer to pass same references
* Being called for each value while cloning. Return true to prevent cloning for the incoming value and pass the same reference instead.
*
* * * *
* Example:
* ```typescript
* import { clone } from "@thalesrc/js-utils/object";
*
* const john = { age: 20, willBeReferenced: true };
* const jane = { age: 25, willBeReferenced: false };
*
* const array = [john, jane];
*
* const clonedArray = clone(array, {valueFiltererToRefer: person => person.willBeReferenced });
*
* // clonedArray[0] === array[0]
* // clonedArray[1] !== array[1]
* ```
* * * *
* @param value incoming value to be cloned
* @return Return true to pass same reference, false to clone
* @default () => false
*/
valueFiltererToRefer?(value: any): boolean;
/**
* #### Properties which cloning unwanted
* Give the unwanted properties to prevent them being cloned
*
* * * *
* Example:
* ```typescript
* import { clone } from "@thalesrc/js-utils/object";
*
* const object = {
* width: 250,
* element: document.querySelector("div")
* };
*
* const clonedObject = clone(object, {propsToRefer: [ "element" ]});
* // clonedObject.element === object.element
* ```
* * * *
* @default []
*/
propsToRefer?: Array<any>;
/**
* #### Custom Cloner Map
*
* * * *
* Example:
* ```typescript
* import { clone } from "@thalesrc/js-utils/object";
*
* const object = {
* width: 250,
* element: document.querySelector("div")
* };
*
* function divCloner(objectToClone, options, internalData) {
* const newElement = document.createElement("div");
* newElement.classList.add("cloned");
* return newElement;
* }
*
* const customCloners = new Map();
* customCloners.set(HTMLDivElement, divCloner);
*
* const clonedObject = clone(object);
* ```
* * * *
*/
customCloners?: Map<Function, TInstanceCloner>;
}
/**
* #### Internal Data For Cloning Process
*/
export interface IClonerInternalData {
clonedObjects: Map<Object, Object | Symbol>;
parent?: Object;
key?: number | string | symbol;
finalizers: Array<() => void>;
}
// TODO: uncomment the code below and delete polyfill when typedoc supports ts@2.8.x
// type TNonOptionalCloneOptions = Required<ICloneOptions>;
export type PolyfillRequired<T, TNames extends string> = { [P in TNames]: (T & { [name: string]: never })[P] };
/**
* Cloning options with all properties required
* @see ICloneOptions
*/
export type TNonOptionalCloneOptions = PolyfillRequired<ICloneOptions, keyof ICloneOptions>;
/**
* Custom Cloner Function
*/
export type TInstanceCloner = <T>(objectToClone: T, options: TNonOptionalCloneOptions, internalData: IClonerInternalData) => T;
/**
* A placeholder to symbolize the cloning progress of `objectToClone` hasn't finished yet
*/
const CLONING_IN_PROGRESS = Symbol('Cloning In Progress');
/**
* Function Map to clone specific objects types
*/
const DEFAULT_INSTANCE_CLONERS = new Map<Function, TInstanceCloner>();
// Set cloning functions
DEFAULT_INSTANCE_CLONERS.set(Array, arrayCloner);
DEFAULT_INSTANCE_CLONERS.set(Map, mapCloner as any);
DEFAULT_INSTANCE_CLONERS.set(Set, setCloner as any);
DEFAULT_INSTANCE_CLONERS.set(Object, objectCloner as any);
/**
* Default Array Cloner
*/
function arrayCloner(objectToClone, options: TNonOptionalCloneOptions, internalData) {
return (objectToClone as any).map((val, i, arr) => {
if (options.propsToRefer.indexOf(i) > -1) {
return val;
}
return cloner(val, options, {...internalData, parent: arr, key: i});
}) as any;
}
/**
* Default Map Cloner
*/
function mapCloner(objectToClone: Map<any, any>, options: TNonOptionalCloneOptions, internalData) {
const newMap = new Map();
intersection(options.propsToRefer, Array.from(objectToClone.keys())).forEach(key => {
newMap.set(key, objectToClone.get(key));
});
difference(Array.from(objectToClone.keys()), options.propsToRefer).forEach(key => {
newMap.set(key, cloner(objectToClone.get(key), options, {...internalData, key, parent: newMap}));
});
return newMap;
}
/**
* Default Set Cloner
*/
function setCloner(objectToClone: Set<any>, options: TNonOptionalCloneOptions, internalData) {
return new Set(objectToClone);
}
/**
* Default Object Cloner
*/
function objectCloner(objectToClone, options: TNonOptionalCloneOptions, internalData) {
const { propsToRefer } = options;
/**
* New Object Clone
*/
const _clone = {};
/**
* Object cloner
* @param key incoming property of object to clone
*/
function cloneObject(key) {
_clone[key] = cloner(objectToClone[key], options, {...internalData, parent: _clone, key});
}
const allProperties = [...Object.keys(objectToClone), ...Object.getOwnPropertySymbols(objectToClone)];
// Pass unwanted props
intersection(propsToRefer, allProperties).forEach(prop => {
_clone[prop] = objectToClone[prop];
});
// Clone remaining properties
difference(allProperties, propsToRefer).forEach(cloneObject);
return _clone;
}
/**
* #### Deep Clone
*
* A function to recursively clone objects, arrays etc. with [cloning options]{@link ICloneOptions}
*
* *References Functions & Symbols by default*
*
* * * *
* Example:
* ```typescript
* import { clone } from "@thalesrc/js-utils/object";
*
* const object = {a: 1, b: {c: true, d: ["x", "y"]}};
*
* // Clone all
* const clonedObject = clone(object);
* // {a: 1, b: {c: true, d: ["x", "y"]}}
* // object.b.d === clonedObject.b.d // false
*
* // Clone all but reference "d"
* const clonedObject = clone(object, {propsToRefer: ["d"]});
* // {a: 1, b: {c: true, d: ["x", "y"]}}
* // object.b.d === clonedObject.b.d // true
* ```
*
* Static usage example:
* ```typescript
* import "@thalesrc/js-utils/object/static/clone";
*
* const object = {a: 1, b: 2};
* const clonedObject = Object.clone(object); // {a: 1, b: 2}
* ```
* * * *
* @param objectToClone Object to clone
* @param options {ICloneOptions} Cloning Options
* @see {@link ICloneOptions} for more information.
*/
export function clone<T>(
objectToClone: T,
{
instancesToRefer = [],
propsToRefer = [],
valueFiltererToRefer = () => false,
customCloners = new Map()
}: ICloneOptions = <ICloneOptions>{}
): T {
/**
* Whole options with defaults
*/
const mergedCloners = merge(customCloners, DEFAULT_INSTANCE_CLONERS);
const allOptions: TNonOptionalCloneOptions = {instancesToRefer, propsToRefer, valueFiltererToRefer, customCloners: mergedCloners};
const finalizers = [];
const cloned = cloner(objectToClone, allOptions, {clonedObjects: new Map(), finalizers});
finalizers.forEach(callback => {callback(); });
return cloned;
}
function cloner<T>(
objectToClone: T,
allOptions: TNonOptionalCloneOptions,
internalData: IClonerInternalData
): T {
const { instancesToRefer, propsToRefer, valueFiltererToRefer, customCloners } = allOptions;
const { clonedObjects, finalizers, parent, key } = internalData;
// Pass primitives & functions
if (objectToClone === null || !(objectToClone instanceof Object) || objectToClone instanceof Function) {
return objectToClone;
}
// Pass unwanted references
if (instancesToRefer.some(instance => objectToClone instanceof instance)) {
return objectToClone;
}
// Pass filterer results
if (valueFiltererToRefer(objectToClone)) {
return objectToClone;
}
// If cloned before, skip circular cloning
if (clonedObjects.has(objectToClone)) {
if (clonedObjects.get(objectToClone) === CLONING_IN_PROGRESS) {
finalizers.push(() => {
parent[key] = clonedObjects.get(objectToClone);
});
return null;
}
return clonedObjects.get(objectToClone) as T;
}
// Mark object as cloning
clonedObjects.set(objectToClone, CLONING_IN_PROGRESS);
// Clone
const customCloner = Array.from(customCloners.keys()).find(val => objectToClone instanceof val);
const result = customCloners.get(customCloner)(objectToClone, allOptions, {...internalData});
clonedObjects.set(objectToClone, result);
return result;
}