Skip to content

Commit 2f42529

Browse files
authored
[fix] Handle non-primitives in isNumber (#12034)
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.
1 parent 370f6c3 commit 2f42529

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

Diff for: src/helpers/helpers.math.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,15 @@ export function _factorize(value: number) {
5757
return result;
5858
}
5959

60+
/**
61+
* Verifies that attempting to coerce n to string or number won't throw a TypeError.
62+
*/
63+
function isNonPrimitive(n: unknown) {
64+
return typeof n === 'symbol' || (typeof n === 'object' && n !== null && !(Symbol.toPrimitive in n || 'toString' in n || 'valueOf' in n));
65+
}
66+
6067
export function isNumber(n: unknown): n is number {
61-
return !isNaN(parseFloat(n as string)) && isFinite(n as number);
68+
return !isNonPrimitive(n) && !isNaN(parseFloat(n as string)) && isFinite(n as number);
6269
}
6370

6471
export function almostWhole(x: number, epsilon: number) {

Diff for: test/specs/helpers.math.tests.js

+2
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ describe('Chart.helpers.math', function() {
103103
expect(math.isNumber(NaN)).toBe(false);
104104
expect(math.isNumber(undefined)).toBe(false);
105105
expect(math.isNumber('cbc')).toBe(false);
106+
expect(math.isNumber(Symbol())).toBe(false);
107+
expect(math.isNumber(Object.create(null))).toBe(false);
106108
});
107109

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

0 commit comments

Comments
 (0)