clone.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var objectToString = require('./staticObjectToString')
  2. var isArray = require('./isArray')
  3. var isPlainObject = require('./isPlainObject')
  4. var objectMap = require('./objectMap')
  5. var map = require('./map')
  6. function handleObjectAndArrayClone (func, obj, deep) {
  7. return func(obj, deep ? function (val) {
  8. return copyValue(val, deep)
  9. } : function (val) {
  10. return val
  11. })
  12. }
  13. function handleValueClone (val, deep) {
  14. if (deep && val) {
  15. var Ctor = val.constructor;
  16. switch(objectToString.call(val)) {
  17. case "[object Date]":
  18. case "[object RegExp]":
  19. return new Ctor(val.valueOf())
  20. case "[object Set]":
  21. var set = new Ctor()
  22. val.forEach(function (v) {
  23. set.add(v)
  24. })
  25. return set
  26. case "[object Map]":
  27. var map = new Ctor()
  28. val.forEach(function (v, k) {
  29. map.set(k, v)
  30. })
  31. return map
  32. }
  33. }
  34. return val
  35. }
  36. function copyValue (val, deep) {
  37. if (isPlainObject(val)) {
  38. return handleObjectAndArrayClone(objectMap, val, deep)
  39. } else if (isArray(val)) {
  40. return handleObjectAndArrayClone(map, val, deep)
  41. }
  42. return handleValueClone(val, deep)
  43. }
  44. /**
  45. * 浅拷贝/深拷贝
  46. *
  47. * @param {Object} obj 对象/数组
  48. * @param {Boolean} deep 是否深拷贝
  49. * @return {Object}
  50. */
  51. function clone (obj, deep) {
  52. if (obj) {
  53. return copyValue(obj, deep)
  54. }
  55. return obj
  56. }
  57. module.exports = clone