Skip to content

Commit

Permalink
feat(utils): approxEq fn
Browse files Browse the repository at this point in the history
  • Loading branch information
tsa96 committed Dec 20, 2024
1 parent 5025824 commit e9433a8
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
23 changes: 23 additions & 0 deletions libs/util-fn/src/approx-eq.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { approxEq } from './approx-eq';

describe('approxEq', () => {
it('returns true for numbers within the default threshold', () => {
expect(approxEq(1.0000001, 1.0000002)).toBe(true);
});

it('returns false for numbers outside the default threshold', () => {
expect(approxEq(1.000001, 1.00001)).toBe(false);
});

it('returns true for numbers within a custom threshold', () => {
expect(approxEq(1.0001, 1.0002, 0.001)).toBe(true);
});

it('returns false for numbers outside a custom threshold', () => {
expect(approxEq(1.0001, 1.0002, 0.00001)).toBe(false);
});

it('returns true for identical numbers', () => {
expect(approxEq(1, 1)).toBe(true);
});
});
4 changes: 4 additions & 0 deletions libs/util-fn/src/approx-eq.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** Float equals check with threshold */
export function approxEq(A: number, B: number, threshold = 1e-6): boolean {
return Math.abs(A - B) < threshold;
}
1 change: 1 addition & 0 deletions libs/util-fn/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export * from './extract-prefix-from-map-name';
export * from './leaderboard-key';
export * from './omit';
export * from './magic';
export * from './approx-eq';

0 comments on commit e9433a8

Please sign in to comment.