index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*!
  2. * shallow-clone <https://github.com/jonschlinkert/shallow-clone>
  3. *
  4. * Copyright (c) 2015-present, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. const valueOf = Symbol.prototype.valueOf;
  9. const typeOf = require('kind-of');
  10. function clone(val, deep) {
  11. switch (typeOf(val)) {
  12. case 'array':
  13. return val.slice();
  14. case 'object':
  15. return Object.assign({}, val);
  16. case 'date':
  17. return new val.constructor(Number(val));
  18. case 'map':
  19. return new Map(val);
  20. case 'set':
  21. return new Set(val);
  22. case 'buffer':
  23. return cloneBuffer(val);
  24. case 'symbol':
  25. return cloneSymbol(val);
  26. case 'arraybuffer':
  27. return cloneArrayBuffer(val);
  28. case 'float32array':
  29. case 'float64array':
  30. case 'int16array':
  31. case 'int32array':
  32. case 'int8array':
  33. case 'uint16array':
  34. case 'uint32array':
  35. case 'uint8clampedarray':
  36. case 'uint8array':
  37. return cloneTypedArray(val);
  38. case 'regexp':
  39. return cloneRegExp(val);
  40. case 'error':
  41. return Object.create(val);
  42. default: {
  43. return val;
  44. }
  45. }
  46. }
  47. function cloneRegExp(val) {
  48. const flags = val.flags !== void 0 ? val.flags : (/\w+$/.exec(val) || void 0);
  49. const re = new val.constructor(val.source, flags);
  50. re.lastIndex = val.lastIndex;
  51. return re;
  52. }
  53. function cloneArrayBuffer(val) {
  54. const res = new val.constructor(val.byteLength);
  55. new Uint8Array(res).set(new Uint8Array(val));
  56. return res;
  57. }
  58. function cloneTypedArray(val, deep) {
  59. return new val.constructor(val.buffer, val.byteOffset, val.length);
  60. }
  61. function cloneBuffer(val) {
  62. const len = val.length;
  63. const buf = Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : Buffer.from(len);
  64. val.copy(buf);
  65. return buf;
  66. }
  67. function cloneSymbol(val) {
  68. return valueOf ? Object(valueOf.call(val)) : {};
  69. }
  70. /**
  71. * Expose `clone`
  72. */
  73. module.exports = clone;