Created
January 16, 2020 19:03
-
-
Save JakeTheCorn/a4bc2360094958f852f34bd1ed88cde5 to your computer and use it in GitHub Desktop.
Utility function for asserting if a string is a valid float. This assumes integers are not floats.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isFloatString(subject: unknown): boolean { | |
if (typeof subject !== 'string') { | |
return false | |
} | |
return /^[+-]?\d+(\.\d+)$/.test(subject) | |
} | |
// tests | |
const tables = [ | |
table('3.33', true), | |
table('3', false), | |
table(undefined, false), | |
table('3.333.33', false) | |
] | |
describe('isFloatString(subject: unknown): boolean', () => { | |
tables.forEach(t => { | |
it(`returns ${JSON.stringify(t.expectation)} when given ${JSON.stringify(t.input)}`, () => { | |
const result = isFloatString(t.input) | |
expect(result).toEqual(t.expectation) | |
}) | |
}) | |
}) | |
function table(input, expectation) { return { input, expectation } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment