Skip to content

Commit

Permalink
feat(core): add equiv utils
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Dec 17, 2024
1 parent 1f80a04 commit 6bae70c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/core/src/api/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@ export type TypedArray =
| Uint32Array;

export interface Utils {
/**
* Checks given arguments for value-based equality. Supports the following
* types:
*
* - JS primitives (boolean, number, string)
* - Arrays (incl. nested)
* - TypedArrays
* - Date
* - RegExp
*
* @param a
* @param b
*/
equiv(a: any, b: any): boolean;
/**
* Pairwise applies {@link Utils.equiv} to all items of the two given
* arraylike arguments and returns true if it successful.
*
* @param a
* @param b
*/
equivArrayLike(a: ArrayLike<any>, b: ArrayLike<any>): boolean;
/**
* Throws an error if `x` is non-truthy, otherwise returns `x`.
*
Expand Down
24 changes: 24 additions & 0 deletions packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,27 @@ export const formatValuePrec = (step: number) => {
const prec = valuePrec(step);
return (x: number) => x.toFixed(prec);
};

export const equiv = (a: any, b: any) => {
if (a === b) return true;
if (a == null) return b == null;
if (b == null) return a == null;
if (isString(a) || isNumber(a)) return a === b;
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
}
if (a instanceof RegExp && b instanceof RegExp) {
return a.toString() === b.toString();
}
if (a.length != null && b.length != null) {
return equivArrayLike(a, b);
}
return a === b || (a !== a && b !== b);
};

export const equivArrayLike = (a: ArrayLike<any>, b: ArrayLike<any>) => {
if (a.length !== b.length) return false;
let i = a.length;
while (i-- > 0 && equiv(a[i], b[i]));
return i < 0;
};

0 comments on commit 6bae70c

Please sign in to comment.