| 12 | * @return {*} clone |
| 13 | */ |
| 14 | export function clone (x) { |
| 15 | const type = typeof x |
| 16 | |
| 17 | // immutable primitive types |
| 18 | if (type === 'number' || type === 'bigint' || type === 'string' || type === 'boolean' || |
| 19 | x === null || x === undefined) { |
| 20 | return x |
| 21 | } |
| 22 | |
| 23 | // use clone function of the object when available |
| 24 | if (typeof x.clone === 'function') { |
| 25 | return x.clone() |
| 26 | } |
| 27 | |
| 28 | // array |
| 29 | if (Array.isArray(x)) { |
| 30 | return x.map(function (value) { |
| 31 | return clone(value) |
| 32 | }) |
| 33 | } |
| 34 | |
| 35 | if (x instanceof Date) return new Date(x.valueOf()) |
| 36 | if (isBigNumber(x)) return x // bignumbers are immutable |
| 37 | |
| 38 | // object |
| 39 | if (isObject(x)) { |
| 40 | return mapObject(x, clone) |
| 41 | } |
| 42 | |
| 43 | if (type === 'function') { |
| 44 | // we assume that the function is immutable |
| 45 | return x |
| 46 | } |
| 47 | |
| 48 | throw new TypeError(`Cannot clone: unknown type of value (value: ${x})`) |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Apply map to all properties of an object |