diff --git a/String/IsNumeric.js b/String/IsNumeric.js new file mode 100644 index 0000000000..aee9c10551 --- /dev/null +++ b/String/IsNumeric.js @@ -0,0 +1,21 @@ +/** + * @function isNumeric + * @description Checks whether a string represents a valid numeric value. + * Supports integers, floats, and negative numbers. + * @param {string} str - The input string to check + * @returns {boolean} - True if the string is numeric, false otherwise + * @see https://en.wikipedia.org/wiki/Numeric_string + * @example isNumeric("123") => true + * @example isNumeric("-45.6") => true + * @example isNumeric("abc") => false + * @example isNumeric("12.3.4") => false + */ +const isNumeric = (str) => { + if (typeof str !== 'string') { + throw new TypeError('Input must be a string') + } + if (str.trim() === '') return false + return !isNaN(str) && !isNaN(parseFloat(str)) +} + +export { isNumeric } diff --git a/String/test/IsNumeric.test.js b/String/test/IsNumeric.test.js new file mode 100644 index 0000000000..d735f7cf99 --- /dev/null +++ b/String/test/IsNumeric.test.js @@ -0,0 +1,51 @@ +import { isNumeric } from '../IsNumeric.js' + +describe('isNumeric', () => { + test("isNumeric('123') returns true", () => { + expect(isNumeric('123')).toBe(true) + }) + + test("isNumeric('-45.6') returns true", () => { + expect(isNumeric('-45.6')).toBe(true) + }) + + test("isNumeric('0') returns true", () => { + expect(isNumeric('0')).toBe(true) + }) + + test("isNumeric('3.14') returns true", () => { + expect(isNumeric('3.14')).toBe(true) + }) + + test("isNumeric('abc') returns false", () => { + expect(isNumeric('abc')).toBe(false) + }) + + test("isNumeric('12.3.4') returns false", () => { + expect(isNumeric('12.3.4')).toBe(false) + }) + + test("isNumeric('') returns false", () => { + expect(isNumeric('')).toBe(false) + }) + + test("isNumeric(' ') returns false", () => { + expect(isNumeric(' ')).toBe(false) + }) + + test("isNumeric('123abc') returns false", () => { + expect(isNumeric('123abc')).toBe(false) + }) + + test("isNumeric('-0') returns true", () => { + expect(isNumeric('-0')).toBe(true) + }) + + test('throws TypeError for non-string input', () => { + expect(() => isNumeric(123)).toThrow(TypeError) + }) + + test('throws TypeError for null input', () => { + expect(() => isNumeric(null)).toThrow(TypeError) + }) +})