Skip to content

Commit

Permalink
Merge pull request citrineos#255 from citrineos/feature/add-deep-equals
Browse files Browse the repository at this point in the history
Added deepEqual method for object comparison
  • Loading branch information
ChrisWeissmann authored Sep 13, 2024
2 parents 166349a + e27972b commit 92a69e9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
34 changes: 34 additions & 0 deletions 00_Base/src/assertion/assertion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,37 @@ export function assert(
export function notNull(object: any): boolean {
return object !== undefined && object !== null;
}

/**
* Ensures that obj2 contains all keys from obj1.
* @param obj1
* @param obj2
* @returns
*/
export function deepDirectionalEqual(obj1: any, obj2: any, seenObjects = new WeakSet()): boolean {
if (obj1 === obj2) return true;

if (typeof obj1 !== 'object' || obj1 === null ||
typeof obj2 !== 'object' || obj2 === null) {
return false;
}

// Check if obj1 has already been seen to avoid cycles
if (seenObjects.has(obj1)) {
return true; // If we've already seen obj1, we assume it's equivalent.
}

// Add obj1 to the seen set
seenObjects.add(obj1);

const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);

for (const key of keys1) {
if (!keys2.includes(key) || !deepDirectionalEqual(obj1[key], obj2[key], seenObjects)) {
return false;
}
}

return true;
}
2 changes: 1 addition & 1 deletion 00_Base/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ export { HttpHeader } from './interfaces/api/http.header';
export { HttpStatus } from './interfaces/api/http.status';
export { Money } from './money/Money';
export { Currency, CurrencyCode } from './money/Currency';
export { assert, notNull } from './assertion/assertion';
export { assert, notNull, deepDirectionalEqual } from './assertion/assertion';
export { UnauthorizedError } from './interfaces/api/exception/UnauthorizedError';
export { AuthorizationSecurity } from './interfaces/api/AuthorizationSecurity';
export { Ajv };

0 comments on commit 92a69e9

Please sign in to comment.