Skip to content

Commit

Permalink
feat(utils): Add isNaN function (#4759)
Browse files Browse the repository at this point in the history
This adds a function, `isNaN`, to our `is` module. While it's true that there is a built-in function of the same name, it assumes it's being passed a number (which messes up types), whereas the function introduced here makes no such assumptions.
  • Loading branch information
lobsterkatie committed Mar 23, 2022
1 parent 20b3e38 commit 1852e6b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
12 changes: 12 additions & 0 deletions packages/utils/src/is.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,18 @@ export function isThenable(wat: any): wat is PromiseLike<any> {
export function isSyntheticEvent(wat: unknown): boolean {
return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
}

/**
* Checks whether given value is NaN
* {@link isNaN}.
*
* @param wat A value to be checked.
* @returns A boolean representing the result.
*/
export function isNaN(wat: unknown): boolean {
return typeof wat === 'number' && wat !== wat;
}

/**
* Checks whether given value's type is an instance of provided constructor.
* {@link isInstanceOf}.
Expand Down
26 changes: 25 additions & 1 deletion packages/utils/test/is.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { isDOMError, isDOMException, isError, isErrorEvent, isInstanceOf, isPrimitive, isThenable } from '../src/is';
import {
isDOMError,
isDOMException,
isError,
isErrorEvent,
isInstanceOf,
isNaN,
isPrimitive,
isThenable,
} from '../src/is';
import { supportsDOMError, supportsDOMException, supportsErrorEvent } from '../src/supports';
import { resolvedSyncPromise } from '../src/syncpromise';

Expand Down Expand Up @@ -110,3 +119,18 @@ describe('isInstanceOf()', () => {
expect(isInstanceOf(new Error('wat'), undefined)).toEqual(false);
});
});

describe('isNaN()', () => {
test('should work as advertised', () => {
expect(isNaN(NaN)).toEqual(true);

expect(isNaN(null)).toEqual(false);
expect(isNaN(true)).toEqual(false);
expect(isNaN('foo')).toEqual(false);
expect(isNaN(42)).toEqual(false);
expect(isNaN({})).toEqual(false);
expect(isNaN([])).toEqual(false);
expect(isNaN(new Error('foo'))).toEqual(false);
expect(isNaN(new Date())).toEqual(false);
});
});

0 comments on commit 1852e6b

Please sign in to comment.