Created
January 16, 2020 19:09
-
-
Save JakeTheCorn/48c28441a8822591da46eb755d59c8e6 to your computer and use it in GitHub Desktop.
Utility function that returns true if it receives a valid int -- not an int string.
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 isInt(subject: unknown): boolean { | |
if (typeof subject !== 'number') { | |
return false | |
} | |
const str = String(subject) | |
return /^[0-9]+$/.test(str) | |
} | |
// tests | |
const tables = [ | |
table(3.33, false), | |
table(3, true), | |
table(33, true), | |
table('33', false, 'returns false for int strings'), | |
table(undefined, false), | |
table('3.333.33', false) | |
] | |
describe('isInt(subject: unknown): boolean', () => { | |
tables.forEach(t => { | |
it(t.message || `returns ${JSON.stringify(t.expectation)} when given ${JSON.stringify(t.input)}`, () => { | |
const result = isInt(t.input) | |
expect(result).toEqual(t.expectation) | |
}) | |
}) | |
}) | |
function table(input, expectation, message?) { return { input, expectation, message } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment