From 076d9ff8f252fefbf24f91c3c8b4ab9ec6e35496 Mon Sep 17 00:00:00 2001 From: Younho Choo Date: Tue, 4 Jan 2022 07:51:36 +0900 Subject: [PATCH] Add `isInfinite()` (#29) --- readme.md | 1 + source/index.ts | 1 + source/is-infinite.ts | 10 ++++++++++ test/is-infinite.ts | 18 ++++++++++++++++++ 4 files changed, 30 insertions(+) create mode 100644 source/is-infinite.ts create mode 100644 test/is-infinite.ts diff --git a/readme.md b/readme.md index 67a4ad2..09bd3d7 100644 --- a/readme.md +++ b/readme.md @@ -30,6 +30,7 @@ import {isDefined} from 'ts-extras'; - [`isDefined`](source/is-defined.ts) - Check whether a value is defined (not `null` or `undefined`). - [`isEmpty`](source/is-empty.ts) - Check whether an array is empty. - [`assertError`](source/assert-error.ts) - Assert that the given value is an `Error`. +- [`isInfinite`](source/is-infinite.ts) - Check whether a value is infinite. **Improved builtin** diff --git a/source/index.ts b/source/index.ts index 0db1fd0..9521a09 100644 --- a/source/index.ts +++ b/source/index.ts @@ -4,6 +4,7 @@ export {assertError} from './assert-error.js'; export {isDefined} from './is-defined.js'; export {isEmpty} from './is-empty.js'; export {isFinite} from './is-finite.js'; +export {isInfinite} from './is-infinite.js'; export {isInteger} from './is-integer.js'; export {isSafeInteger} from './is-safe-integer.js'; export {objectEntries} from './object-entries.js'; diff --git a/source/is-infinite.ts b/source/is-infinite.ts new file mode 100644 index 0000000..22d7d47 --- /dev/null +++ b/source/is-infinite.ts @@ -0,0 +1,10 @@ +import {NegativeInfinity, PositiveInfinity} from 'type-fest'; + +/** +Check whether a value is infinite. + +@category Type guard +*/ +export function isInfinite(value: unknown): value is NegativeInfinity | PositiveInfinity { + return !Number.isNaN(value) && !Number.isFinite(value); +} diff --git a/test/is-infinite.ts b/test/is-infinite.ts new file mode 100644 index 0000000..cb29219 --- /dev/null +++ b/test/is-infinite.ts @@ -0,0 +1,18 @@ +import test from 'ava'; +import {expectTypeOf} from 'expect-type'; +import {NegativeInfinity, PositiveInfinity} from 'type-fest'; +import {isInfinite} from '../source/index.js'; + +test('isInfinite()', t => { + t.false(isInfinite(123)); + t.true(isInfinite(Number.POSITIVE_INFINITY)); + t.true(isInfinite(Number.NEGATIVE_INFINITY)); + + const number_ = 123 as number; + + if (isInfinite(number_)) { + expectTypeOf(number_); + } else { + expectTypeOf(number_); + } +});