2022-10-18 04:33:31 -07:00
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */
|
|
|
|
export const deepCopy = <T>(source: T): T => {
|
|
|
|
let clone: any;
|
|
|
|
let i: any;
|
|
|
|
const hasOwnProp = Object.prototype.hasOwnProperty.bind(source);
|
|
|
|
// Primitives & Null
|
|
|
|
if (typeof source !== 'object' || source === null) {
|
|
|
|
return source;
|
|
|
|
}
|
|
|
|
// Date
|
|
|
|
if (source instanceof Date) {
|
|
|
|
return new Date(source.getTime()) as T;
|
|
|
|
}
|
|
|
|
// Array
|
|
|
|
if (Array.isArray(source)) {
|
|
|
|
clone = [];
|
|
|
|
const len = source.length;
|
|
|
|
for (i = 0; i < len; i++) {
|
|
|
|
clone[i] = deepCopy(source[i]);
|
|
|
|
}
|
|
|
|
return clone;
|
|
|
|
}
|
|
|
|
// Object
|
|
|
|
clone = {};
|
|
|
|
for (i in source) {
|
|
|
|
if (hasOwnProp(i)) {
|
|
|
|
clone[i] = deepCopy((source as any)[i]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return clone;
|
|
|
|
};
|
|
|
|
// eslint-enable
|
2022-10-21 11:52:43 -07:00
|
|
|
|
2022-10-24 03:48:16 -07:00
|
|
|
type MutuallyExclusive<T, U> =
|
|
|
|
| (T & { [k in Exclude<keyof U, keyof T>]?: never })
|
|
|
|
| (U & { [k in Exclude<keyof T, keyof U>]?: never });
|
|
|
|
|
|
|
|
type JSONParseOptions<T> = MutuallyExclusive<{ errorMessage: string }, { fallbackValue: T }>;
|
|
|
|
|
|
|
|
export const jsonParse = <T>(jsonString: string, options?: JSONParseOptions<T>): T => {
|
2022-10-21 11:52:43 -07:00
|
|
|
try {
|
|
|
|
return JSON.parse(jsonString) as T;
|
|
|
|
} catch (error) {
|
2022-10-24 03:48:16 -07:00
|
|
|
if (options?.fallbackValue !== undefined) {
|
2022-10-21 11:52:43 -07:00
|
|
|
return options.fallbackValue;
|
2022-10-24 03:48:16 -07:00
|
|
|
} else if (options?.errorMessage) {
|
2022-10-21 11:52:43 -07:00
|
|
|
throw new Error(options.errorMessage);
|
|
|
|
}
|
2022-10-24 03:48:16 -07:00
|
|
|
|
2022-10-21 11:52:43 -07:00
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
};
|