Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Created January 16, 2020 19:03
Show Gist options
  • Save JakeTheCorn/a4bc2360094958f852f34bd1ed88cde5 to your computer and use it in GitHub Desktop.
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.
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