[6a3a178] | 1 | import { isPlainObject, isArray } from 'is-what'
|
---|
| 2 |
|
---|
| 3 | type PlainObject = { [key in string | symbol]: any }
|
---|
| 4 |
|
---|
| 5 | function 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 |
|
---|
| 26 | export 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 | */
|
---|
| 38 | export 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 | }
|
---|