1 | function set(obj, key, val) {
|
---|
2 | if (typeof val.value === 'object') val.value = klona(val.value);
|
---|
3 | if (!val.enumerable || val.get || val.set || !val.configurable || !val.writable || key === '__proto__') {
|
---|
4 | Object.defineProperty(obj, key, val);
|
---|
5 | } else obj[key] = val.value;
|
---|
6 | }
|
---|
7 |
|
---|
8 | export function klona(x) {
|
---|
9 | if (typeof x !== 'object') return x;
|
---|
10 |
|
---|
11 | var i=0, k, list, tmp, str=Object.prototype.toString.call(x);
|
---|
12 |
|
---|
13 | if (str === '[object Object]') {
|
---|
14 | tmp = Object.create(x.__proto__ || null);
|
---|
15 | } else if (str === '[object Array]') {
|
---|
16 | tmp = Array(x.length);
|
---|
17 | } else if (str === '[object Set]') {
|
---|
18 | tmp = new Set;
|
---|
19 | x.forEach(function (val) {
|
---|
20 | tmp.add(klona(val));
|
---|
21 | });
|
---|
22 | } else if (str === '[object Map]') {
|
---|
23 | tmp = new Map;
|
---|
24 | x.forEach(function (val, key) {
|
---|
25 | tmp.set(klona(key), klona(val));
|
---|
26 | });
|
---|
27 | } else if (str === '[object Date]') {
|
---|
28 | tmp = new Date(+x);
|
---|
29 | } else if (str === '[object RegExp]') {
|
---|
30 | tmp = new RegExp(x.source, x.flags);
|
---|
31 | } else if (str === '[object DataView]') {
|
---|
32 | tmp = new x.constructor( klona(x.buffer) );
|
---|
33 | } else if (str === '[object ArrayBuffer]') {
|
---|
34 | tmp = x.slice(0);
|
---|
35 | } else if (str.slice(-6) === 'Array]') {
|
---|
36 | // ArrayBuffer.isView(x)
|
---|
37 | // ~> `new` bcuz `Buffer.slice` => ref
|
---|
38 | tmp = new x.constructor(x);
|
---|
39 | }
|
---|
40 |
|
---|
41 | if (tmp) {
|
---|
42 | for (list=Object.getOwnPropertySymbols(x); i < list.length; i++) {
|
---|
43 | set(tmp, list[i], Object.getOwnPropertyDescriptor(x, list[i]));
|
---|
44 | }
|
---|
45 |
|
---|
46 | for (i=0, list=Object.getOwnPropertyNames(x); i < list.length; i++) {
|
---|
47 | if (Object.hasOwnProperty.call(tmp, k=list[i]) && tmp[k] === x[k]) continue;
|
---|
48 | set(tmp, k, Object.getOwnPropertyDescriptor(x, k));
|
---|
49 | }
|
---|
50 | }
|
---|
51 |
|
---|
52 | return tmp || x;
|
---|
53 | }
|
---|