Skip to content

Commit

Permalink
feat: new function - isNumberLike
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed May 26, 2023
1 parent 8c2d7cd commit 0ffe623
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ pnpm add @utopia-utils/share
* isObject
* isIntegerKey
* isEmpty [source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/share/src/isEmpty.ts)
* isNumberLike [source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/share/src/isNumberLike.ts)
* isValidUrl [source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/share/src/isValidUrl.ts)
------

Expand Down
49 changes: 49 additions & 0 deletions packages/share/src/isNumberLike.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest'

import { isNumberLike } from './isNumberLike'

describe('isNumberLike', () => {
it('should return true', () => {
const testCases = [
[0.2, true],
[5, true],
['0.2', true],
['5', true],
[-1, true],
[Infinity, true],
['Infinity', true],
[1.1e2, true],
['1.1e2', true],
[Number.EPSILON, true],
[Number.MAX_SAFE_INTEGER, true],
[Number.MAX_VALUE, true],
[Number.MIN_SAFE_INTEGER, true],
[Number.MIN_VALUE, true],
]
testCases.forEach(([input, expected]) => {
expect(isNumberLike(input)).toBe(expected)
})
})

it('should return false', () => {
const testCases = [
[NaN, false],
['NaN', false],
['', false],
[' ', false],
['-', false],
[null, false],
[undefined, false],
['1.1.1', false],
[[], false],
[{}, false],
['1.1.e2', false],
[false, false],
[true, false],
[function foo() {}, false],
]
testCases.forEach(([input, expected]) => {
expect(isNumberLike(input)).toBe(expected)
})
})
})
14 changes: 14 additions & 0 deletions packages/share/src/isNumberLike.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* The function checks if a value is a number or a string that can be converted to a number.
* @param {unknown} val
* @returns {boolean}
* @example
* ```ts
* 1, '1', 1.1, '1.1', -1, '-1', Infinity, 'Infinity', 1.1e2 => true
* NaN, 'NaN', '', ' ', null, undefined, '1.1.1', [], {}, '1.1.e2', false, true => false
* ```
*/
export function isNumberLike(val: unknown) {
return (typeof val === 'number' && !Number.isNaN(val))
|| (typeof val === 'string' && val.trim() !== '' && !Number.isNaN(Number(val)))
}

0 comments on commit 0ffe623

Please sign in to comment.