租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.0 KiB

3 months ago
  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. };