index.js 1.6 KB

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