index.js 993 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function klona(x) {
  2. if (typeof x !== 'object') return x;
  3. var k, tmp, str=Object.prototype.toString.call(x);
  4. if (str === '[object Object]') {
  5. if (x.constructor !== Object && typeof x.constructor === 'function') {
  6. tmp = new x.constructor();
  7. for (k in x) {
  8. if (x.hasOwnProperty(k) && tmp[k] !== x[k]) {
  9. tmp[k] = klona(x[k]);
  10. }
  11. }
  12. } else {
  13. tmp = {}; // null
  14. for (k in x) {
  15. if (k === '__proto__') {
  16. Object.defineProperty(tmp, k, {
  17. value: klona(x[k]),
  18. configurable: true,
  19. enumerable: true,
  20. writable: true,
  21. });
  22. } else {
  23. tmp[k] = klona(x[k]);
  24. }
  25. }
  26. }
  27. return tmp;
  28. }
  29. if (str === '[object Array]') {
  30. k = x.length;
  31. for (tmp=Array(k); k--;) {
  32. tmp[k] = klona(x[k]);
  33. }
  34. return tmp;
  35. }
  36. if (str === '[object Date]') {
  37. return new Date(+x);
  38. }
  39. if (str === '[object RegExp]') {
  40. tmp = new RegExp(x.source, x.flags);
  41. tmp.lastIndex = x.lastIndex;
  42. return tmp;
  43. }
  44. return x;
  45. }
  46. exports.klona = klona;