is-deep-equals.ts 1.6 KB

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