| 12345678910111213141516171819202122232425262728293031323334353637 |
- export function deepCopy<T>(obj: T, keys?: string[]): T {
- // Handle Object
- if (obj instanceof String) {
- return (obj + '') as unknown as T;
- } else if (obj instanceof Date) {
- return new Date(obj.getTime()) as unknown as T;
- } else if (obj instanceof Array) {
- const copy = Array(obj.length);
- for (let i = 0, len = obj.length; i < len; i++) {
- copy[i] = deepCopy(obj[i]);
- }
- return copy as unknown as T;
- } else if (obj instanceof Set) {
- const copy = new Set();
- obj.forEach(value => {
- copy.add(deepCopy(value));
- });
- return copy as unknown as T;
- } else if (obj instanceof Map) {
- const copy = new Map();
- obj.forEach((value, key) => {
- copy.set(key, deepCopy(value));
- });
- return copy as unknown as T;
- } else if (obj instanceof Object) {
- const copy: { [key: string]: any } = {};
- for (const attr in obj) {
- if (typeof keys !== 'undefined' && !keys.includes(attr)) {
- continue;
- }
- if (Object.getOwnPropertyNames(obj).includes(attr)) copy[attr] = deepCopy((obj as { [key: string]: any })[attr]);
- }
- return copy as unknown as T;
- } else {
- return obj;
- }
- }
|