Created
July 3, 2020 19:12
-
-
Save simaodeveloper/4a3c387e5d98a5cb94b6b6aa67e0520b to your computer and use it in GitHub Desktop.
A tiny library to help test the type of a value
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
const firstLetterUpperCase = str => | |
str.replace(/(^\w)/, m => m.toUpperCase()); | |
const firstLetterLowerCase = str => | |
str.replace(/(^\w)/, m => m.toLowerCase()); | |
const toString = value => | |
Object.prototype.toString.call(value); | |
const isType = (type, value) => | |
`[object ${firstLetterUpperCase(type)}]` === toString(value); | |
export default { | |
is(type, value) { | |
if (!isType('string', type)) { | |
throw new Error('type required must be a string!'); | |
} | |
if (arguments.length === 2) { | |
return isType(type, value); | |
} | |
return value => isType(type, value); | |
}, | |
of(value) { | |
const type = toString(value) | |
.replace(/^\[object\s?(\w+)\]$/, '$1'); | |
return firstLetterLowerCase(type); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment