Skip to content

Instantly share code, notes, and snippets.

@simaodeveloper
Created July 3, 2020 19:12
Show Gist options
  • Save simaodeveloper/4a3c387e5d98a5cb94b6b6aa67e0520b to your computer and use it in GitHub Desktop.
Save simaodeveloper/4a3c387e5d98a5cb94b6b6aa67e0520b to your computer and use it in GitHub Desktop.
A tiny library to help test the type of a value
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