-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclone.ts
38 lines (33 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
33
34
35
36
37
38
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
import { isPrimitive } from "..";
/**
* Creates a shallow copy of the given object/value.
* @param {*} obj value to clone
* @returns {*} shallow clone of the given value
*/
export function clone<T>(obj: T): T {
// Primitive values do not need cloning.
if (isPrimitive(obj)) {
return obj;
}
// Binding a function to an empty object creates a
// copy function.
if (typeof obj === "function") {
return obj.bind({});
}
// Access the constructor and create a new object.
// This method can create an array as well.
const newObj = new ((obj as object).constructor as { new (): T })();
// Assign the props.
Object.getOwnPropertyNames(obj).forEach((prop) => {
// Bypass type checking since the primitive cases
// are already checked in the beginning
(newObj as any)[prop] = (obj as any)[prop];
});
return newObj;
}