is-deep-equals.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const isPrimitiveComparison = (value1: unknown, value2: unknown): boolean => {
  2. return (
  3. value1 === null ||
  4. value2 === null ||
  5. typeof value1 !== 'object' ||
  6. typeof value2 !== 'object'
  7. );
  8. };
  9. export const isDeepEquals = <T extends object>(
  10. obj1: T,
  11. obj2: T,
  12. visited = new WeakMap(),
  13. ): boolean => {
  14. // If references are identical, return true
  15. if (obj1 === obj2) {
  16. return true;
  17. }
  18. // Use simple comparison for null or primitive values
  19. if (isPrimitiveComparison(obj1, obj2)) {
  20. return obj1 === obj2;
  21. }
  22. // Check for circular references
  23. if (visited.has(obj1)) {
  24. return visited.get(obj1) === obj2;
  25. }
  26. visited.set(obj1, obj2);
  27. // Compare number of properties
  28. const typedKeys1 = Object.keys(obj1) as (keyof typeof obj1)[];
  29. const typedKeys2 = Object.keys(obj2) as (keyof typeof obj2)[];
  30. if (typedKeys1.length !== typedKeys2.length) {
  31. return false;
  32. }
  33. // Compare all properties
  34. return typedKeys1.every((key) => {
  35. const val1 = obj1[key];
  36. const val2 = obj2[key];
  37. // Handle arrays comparison
  38. if (Array.isArray(val1) && Array.isArray(val2)) {
  39. if (val1.length !== val2.length) {
  40. return false;
  41. }
  42. return val1.every((item, i) => {
  43. if (!isPrimitiveComparison(item, val2[i])) {
  44. return isDeepEquals(item, val2[i], visited);
  45. }
  46. return item === val2[i];
  47. });
  48. }
  49. // Recursively compare objects
  50. if (!isPrimitiveComparison(val1, val2)) {
  51. return isDeepEquals(val1 as object, val2 as object, visited);
  52. }
  53. // Compare primitive values
  54. return val1 === val2;
  55. });
  56. };