Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(range) Handle nullish values #30070

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions core/src/utils/floating-point/floating-point.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,24 @@ describe('floating point utils', () => {
const n = getDecimalPlaces(5);
expect(n).toBe(0);
});

it('should handle nullish values', () => {
expect(getDecimalPlaces(undefined as any)).toBe(0);
expect(getDecimalPlaces(null as any)).toBe(0);
expect(getDecimalPlaces(NaN as any)).toBe(0);
});
});

describe('roundToMaxDecimalPlaces', () => {
it('should round to the highest number of places as references', async () => {
const n = roundToMaxDecimalPlaces(5.12345, 1.12, 2.123);
expect(n).toBe(5.123);
});

it('should handle nullish values', () => {
expect(roundToMaxDecimalPlaces(undefined as any)).toBe(0);
expect(roundToMaxDecimalPlaces(null as any)).toBe(0);
expect(roundToMaxDecimalPlaces(NaN as any)).toBe(0);
})
});
});
4 changes: 4 additions & 0 deletions core/src/utils/floating-point/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { isSafeNumber } from '../type-guards.ts';

export function getDecimalPlaces(n: number) {
if (!isSafeNumber(n)) return 0;
if (n % 1 === 0) return 0;
return n.toString().split('.')[1].length;
}
Expand Down Expand Up @@ -36,6 +39,7 @@ export function getDecimalPlaces(n: number) {
* be used as a reference for the desired specificity.
*/
export function roundToMaxDecimalPlaces(n: number, ...references: number[]) {
if (!isSafeNumber(n)) return 0;
const maxPlaces = Math.max(...references.map((r) => getDecimalPlaces(r)));
return Number(n.toFixed(maxPlaces));
}
6 changes: 6 additions & 0 deletions core/src/utils/type-guards.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Checks input for usable number. Not NaN and not Infinite.
*/
export const isSafeNumber = (input: unknown): input is number => {
return typeof input === 'number' && !isNaN(input) && isFinite(input);
};
Loading