clone.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var kindOf = require('./kindOf');
  2. var isPlainObject = require('./isPlainObject');
  3. var mixIn = require('../object/mixIn');
  4. /**
  5. * Clone native types.
  6. */
  7. function clone(val){
  8. switch (kindOf(val)) {
  9. case 'Object':
  10. return cloneObject(val);
  11. case 'Array':
  12. return cloneArray(val);
  13. case 'RegExp':
  14. return cloneRegExp(val);
  15. case 'Date':
  16. return cloneDate(val);
  17. default:
  18. return val;
  19. }
  20. }
  21. function cloneObject(source) {
  22. if (isPlainObject(source)) {
  23. return mixIn({}, source);
  24. } else {
  25. return source;
  26. }
  27. }
  28. function cloneRegExp(r) {
  29. var flags = '';
  30. flags += r.multiline ? 'm' : '';
  31. flags += r.global ? 'g' : '';
  32. flags += r.ignorecase ? 'i' : '';
  33. return new RegExp(r.source, flags);
  34. }
  35. function cloneDate(date) {
  36. return new Date(+date);
  37. }
  38. function cloneArray(arr) {
  39. return arr.slice();
  40. }
  41. module.exports = clone;