deepCopy.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { isBuffer } from './isBuffer';
  2. export const deepCopy = obj => {
  3. if (obj === null || typeof obj !== 'object') {
  4. return obj;
  5. }
  6. if (isBuffer(obj)) {
  7. return obj.slice();
  8. }
  9. const copy = Array.isArray(obj) ? [] : {};
  10. Object.keys(obj).forEach(key => {
  11. copy[key] = deepCopy(obj[key]);
  12. });
  13. return copy;
  14. };
  15. export const deepCopyWith = (obj: any, customizer?: (v: any, k: string, o: any) => any) => {
  16. function deepCopyWithHelper(value: any, innerKey: string, innerObject: any) {
  17. const result = customizer!(value, innerKey, innerObject);
  18. if (result !== undefined) return result;
  19. if (value === null || typeof value !== 'object') {
  20. return value;
  21. }
  22. if (isBuffer(value)) {
  23. return value.slice();
  24. }
  25. const copy = Array.isArray(value) ? [] : {};
  26. Object.keys(value).forEach(k => {
  27. copy[k] = deepCopyWithHelper(value[k], k, value);
  28. });
  29. return copy;
  30. }
  31. if (customizer) {
  32. return deepCopyWithHelper(obj, '', null);
  33. } else {
  34. return deepCopy(obj);
  35. }
  36. };