|
| 1 | +// Needed to copy directly from |
| 2 | +// https://github.com/lukeed/klona/blob/master/src/index.js |
| 3 | + |
| 4 | +export function klona(x) { |
| 5 | + if (typeof x !== 'object') return x; |
| 6 | + |
| 7 | + var k, |
| 8 | + tmp, |
| 9 | + str = Object.prototype.toString.call(x); |
| 10 | + |
| 11 | + if (str === '[object Object]') { |
| 12 | + if (x.constructor !== Object && typeof x.constructor === 'function') { |
| 13 | + tmp = new x.constructor(); |
| 14 | + for (k in x) { |
| 15 | + if (x.hasOwnProperty(k) && tmp[k] !== x[k]) { |
| 16 | + tmp[k] = klona(x[k]); |
| 17 | + } |
| 18 | + } |
| 19 | + } else { |
| 20 | + tmp = {}; // null |
| 21 | + for (k in x) { |
| 22 | + if (k === '__proto__') { |
| 23 | + Object.defineProperty(tmp, k, { |
| 24 | + value: klona(x[k]), |
| 25 | + configurable: true, |
| 26 | + enumerable: true, |
| 27 | + writable: true |
| 28 | + }); |
| 29 | + } else { |
| 30 | + tmp[k] = klona(x[k]); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + return tmp; |
| 35 | + } |
| 36 | + |
| 37 | + if (str === '[object Array]') { |
| 38 | + k = x.length; |
| 39 | + for (tmp = Array(k); k--; ) { |
| 40 | + tmp[k] = klona(x[k]); |
| 41 | + } |
| 42 | + return tmp; |
| 43 | + } |
| 44 | + |
| 45 | + if (str === '[object Set]') { |
| 46 | + tmp = new Set(); |
| 47 | + x.forEach(function (val) { |
| 48 | + tmp.add(klona(val)); |
| 49 | + }); |
| 50 | + return tmp; |
| 51 | + } |
| 52 | + |
| 53 | + if (str === '[object Map]') { |
| 54 | + tmp = new Map(); |
| 55 | + x.forEach(function (val, key) { |
| 56 | + tmp.set(klona(key), klona(val)); |
| 57 | + }); |
| 58 | + return tmp; |
| 59 | + } |
| 60 | + |
| 61 | + if (str === '[object Date]') { |
| 62 | + return new Date(+x); |
| 63 | + } |
| 64 | + |
| 65 | + if (str === '[object RegExp]') { |
| 66 | + tmp = new RegExp(x.source, x.flags); |
| 67 | + tmp.lastIndex = x.lastIndex; |
| 68 | + return tmp; |
| 69 | + } |
| 70 | + |
| 71 | + if (str === '[object DataView]') { |
| 72 | + return new x.constructor(klona(x.buffer)); |
| 73 | + } |
| 74 | + |
| 75 | + if (str === '[object ArrayBuffer]') { |
| 76 | + return x.slice(0); |
| 77 | + } |
| 78 | + |
| 79 | + // ArrayBuffer.isView(x) |
| 80 | + // ~> `new` bcuz `Buffer.slice` => ref |
| 81 | + if (str.slice(-6) === 'Array]') { |
| 82 | + return new x.constructor(x); |
| 83 | + } |
| 84 | + |
| 85 | + return x; |
| 86 | +} |
0 commit comments