Skip to content

Commit e5e103c

Browse files
feat: add string isNumeric algorithm
1 parent 5c39e87 commit e5e103c

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎String/IsNumeric.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @function isNumeric
3+
* @description Checks whether a string represents a valid numeric value.
4+
* Supports integers, floats, and negative numbers.
5+
* @param {string} str - The input string to check
6+
* @returns {boolean} - True if the string is numeric, false otherwise
7+
* @see https://en.wikipedia.org/wiki/Numeric_string
8+
* @example isNumeric("123") => true
9+
* @example isNumeric("-45.6") => true
10+
* @example isNumeric("abc") => false
11+
* @example isNumeric("12.3.4") => false
12+
*/
13+
const isNumeric = (str) => {
14+
if (typeof str !== 'string') {
15+
throw new TypeError('Input must be a string')
16+
}
17+
if (str.trim() === '') return false
18+
return !isNaN(str) && !isNaN(parseFloat(str))
19+
}
20+
21+
export { isNumeric }

‎String/test/IsNumeric.test.js‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { isNumeric } from '../IsNumeric.js'
2+
3+
describe('isNumeric', () => {
4+
test("isNumeric('123') returns true", () => {
5+
expect(isNumeric('123')).toBe(true)
6+
})
7+
8+
test("isNumeric('-45.6') returns true", () => {
9+
expect(isNumeric('-45.6')).toBe(true)
10+
})
11+
12+
test("isNumeric('0') returns true", () => {
13+
expect(isNumeric('0')).toBe(true)
14+
})
15+
16+
test("isNumeric('3.14') returns true", () => {
17+
expect(isNumeric('3.14')).toBe(true)
18+
})
19+
20+
test("isNumeric('abc') returns false", () => {
21+
expect(isNumeric('abc')).toBe(false)
22+
})
23+
24+
test("isNumeric('12.3.4') returns false", () => {
25+
expect(isNumeric('12.3.4')).toBe(false)
26+
})
27+
28+
test("isNumeric('') returns false", () => {
29+
expect(isNumeric('')).toBe(false)
30+
})
31+
32+
test("isNumeric(' ') returns false", () => {
33+
expect(isNumeric(' ')).toBe(false)
34+
})
35+
36+
test("isNumeric('123abc') returns false", () => {
37+
expect(isNumeric('123abc')).toBe(false)
38+
})
39+
40+
test("isNumeric('-0') returns true", () => {
41+
expect(isNumeric('-0')).toBe(true)
42+
})
43+
44+
test('throws TypeError for non-string input', () => {
45+
expect(() => isNumeric(123)).toThrow(TypeError)
46+
})
47+
48+
test('throws TypeError for null input', () => {
49+
expect(() => isNumeric(null)).toThrow(TypeError)
50+
})
51+
})

0 commit comments

Comments
 (0)