clone.js 829 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. module.exports = clone;
  2. // via http://stackoverflow.com/a/728694/22617
  3. function clone(obj) {
  4. // Handle the 3 simple types, and null or undefined
  5. if (null === obj || 'object' !== typeof obj) {
  6. return obj;
  7. }
  8. var copy;
  9. // Handle Date
  10. if (obj instanceof Date) {
  11. copy = new Date();
  12. copy.setTime(obj.getTime());
  13. return copy;
  14. }
  15. // Handle Array
  16. if (obj instanceof Array) {
  17. copy = [];
  18. for (var i = 0, len = obj.length; i < len; i++) {
  19. copy[i] = clone(obj[i]);
  20. }
  21. return copy;
  22. }
  23. // Handle Object
  24. if (obj instanceof Object) {
  25. copy = {};
  26. for (var attr in obj) {
  27. if (obj.hasOwnProperty && obj.hasOwnProperty(attr)) {
  28. copy[attr] = clone(obj[attr]);
  29. }
  30. }
  31. return copy;
  32. }
  33. throw new Error('Unable to copy obj! Its type isn\'t supported.');
  34. }