source: trip-planner-front/node_modules/copy-anything/src/index.ts@ 59329aa

Last change on this file since 59329aa was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.7 KB
Line 
1import { isPlainObject, isArray } from 'is-what'
2
3type PlainObject = { [key in string | symbol]: any }
4
5function assignProp (
6 carry: PlainObject,
7 key: string | symbol,
8 newVal: any,
9 originalObject: PlainObject,
10 includeNonenumerable: boolean
11): void {
12 const propType = {}.propertyIsEnumerable.call(originalObject, key)
13 ? 'enumerable'
14 : 'nonenumerable'
15 if (propType === 'enumerable') carry[key as any] = newVal
16 if (includeNonenumerable && propType === 'nonenumerable') {
17 Object.defineProperty(carry, key, {
18 value: newVal,
19 enumerable: false,
20 writable: true,
21 configurable: true,
22 })
23 }
24}
25
26export type Options = { props?: (string | symbol)[]; nonenumerable?: boolean }
27
28/**
29 * Copy (clone) an object and all its props recursively to get rid of any prop referenced of the original object. Arrays are also cloned, however objects inside arrays are still linked.
30 *
31 * @export
32 * @template T
33 * @param {T} target Target can be anything
34 * @param {Options} [options = {}] Options can be `props` or `nonenumerable`
35 * @returns {T} the target with replaced values
36 * @export
37 */
38export function copy<T extends any> (target: T, options: Options = {}): T {
39 if (isArray(target)) return target.map((item) => copy(item, options)) as T
40 if (!isPlainObject(target)) return target
41 const props = Object.getOwnPropertyNames(target)
42 const symbols = Object.getOwnPropertySymbols(target)
43 return [...props, ...symbols].reduce((carry, key) => {
44 if (isArray(options.props) && !options.props.includes(key)) {
45 return carry
46 }
47 const val = target[key]
48 const newVal = copy(val, options)
49 assignProp(carry, key, newVal, target, options.nonenumerable)
50 return carry
51 }, {} as T)
52}
Note: See TracBrowser for help on using the repository browser.