Skip to content

Commit

Permalink
[fix] Handle non-primitives in isNumber (#12034)
Browse files Browse the repository at this point in the history
While investigating chartjs/chartjs-plugin-zoom#928, I found that `isNonPrimitive` will throw TypeError on a Moment.js object after it's passed through Chart.js's options proxy, because the object has its `Symbol.toPrimitive`, `toString`, and `valueOf` all set to null.

(See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion for background reading.)

Since isNumber appears to be a low-level function that can take any arbitrary input, it seems worth letting it handle this case.
  • Loading branch information
joshkel authored Feb 16, 2025
1 parent 370f6c3 commit 2f42529
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/helpers/helpers.math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,15 @@ export function _factorize(value: number) {
return result;
}

/**
* Verifies that attempting to coerce n to string or number won't throw a TypeError.
*/
function isNonPrimitive(n: unknown) {
return typeof n === 'symbol' || (typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n));
}

export function isNumber(n: unknown): n is number {
return !isNaN(parseFloat(n as string)) && isFinite(n as number);
return !isNonPrimitive(n) && !isNaN(parseFloat(n as string)) && isFinite(n as number);
}

export function almostWhole(x: number, epsilon: number) {
Expand Down
2 changes: 2 additions & 0 deletions test/specs/helpers.math.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ describe('Chart.helpers.math', function() {
expect(math.isNumber(NaN)).toBe(false);
expect(math.isNumber(undefined)).toBe(false);
expect(math.isNumber('cbc')).toBe(false);
expect(math.isNumber(Symbol())).toBe(false);
expect(math.isNumber(Object.create(null))).toBe(false);
});

it('should compute shortest distance between angles', function() {
Expand Down

0 comments on commit 2f42529

Please sign in to comment.