compare.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. export namespace Compare {
  6. /**
  7. * 比较,默认浅比较
  8. * @param oldProps
  9. * @param newProps
  10. * @param depth - 比较的深度,默认是 1
  11. * @param partial - 比较对象的局部,默认 true
  12. */
  13. export function isChanged(oldProps: any, newProps: any, depth = 1, partial = true): boolean {
  14. if (oldProps === newProps) return false;
  15. if (depth === 0 || typeof oldProps !== 'object' || typeof newProps !== 'object') {
  16. return oldProps !== newProps;
  17. }
  18. const keys = Object.keys(newProps);
  19. if (!partial) {
  20. const oldKeys = Object.keys(oldProps);
  21. if (keys.length !== oldKeys.length) return true;
  22. }
  23. for (let i = 0, len = keys.length; i < len; i++) {
  24. const key = keys[i];
  25. if (isChanged(oldProps[key], newProps[key], depth - 1, partial)) return true;
  26. }
  27. return false;
  28. }
  29. /**
  30. * 深度比较
  31. * @param oldProps
  32. * @param newProps
  33. * @param partial - 比较对象的局部,默认 true
  34. */
  35. export function isDeepChanged(oldProps: any, newProps: any, partial?: boolean): boolean {
  36. return isChanged(oldProps, newProps, Infinity, partial);
  37. }
  38. export function isArrayShallowChanged(arr1: any[], arr2: any[]): boolean {
  39. if (arr1.length !== arr2.length) return true;
  40. for (let i = 0, len = arr1.length; i < len; i++) {
  41. if (arr1[i] !== arr2[i]) {
  42. return true;
  43. }
  44. }
  45. return false;
  46. }
  47. }