Skip to content

Commit

Permalink
feat: add deepEqual、assert
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxingkang committed Jan 17, 2024
1 parent baf8935 commit 58839f7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/utils/assert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function assert(condition: boolean, message: string) {
if (!condition) {
throw new Error(message);
}
}
44 changes: 44 additions & 0 deletions src/utils/deepEqual.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Compare any two objects
* @param a
* @param b
* @returns true if the objects are deep equal
*/
export function deepEqual(a: any, b: any): boolean {
if (a === b) {
return true;
}
if (!a || !b) {
return false;
}
if (Array.isArray(a)) {
if (!Array.isArray(b) || a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (!deepEqual(a[i], b[i])) {
return false;
}
}
return true;
} else if (Array.isArray(b)) {
return false;
}
if (typeof a === 'object' && typeof b === 'object') {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (const key of aKeys) {
if (!b.hasOwnProperty(key)) {
return false;
}
if (!deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
return false;
}

0 comments on commit 58839f7

Please sign in to comment.