Last active
December 10, 2018 17:42
-
-
Save VitorLuizC/e0979afde0430822f31ed3df7aed2e2a to your computer and use it in GitHub Desktop.
JavaScript micro-function to check vars types
This file contains hidden or 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
| import { is, getType } from './type.js' | |
| const isFields = (fields) => values.every((field) => is(field, 'Object')) | |
| const getName = (value) => { | |
| const names = { | |
| 'String': () => value, | |
| 'Number': () => `Number ${value}`, | |
| 'Array': () => `List (${value.join(', ')})` | |
| } | |
| return names[getType(value)] || 'None' | |
| } |
This file contains hidden or 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
| /** | |
| * Get value's type name. | |
| * @param {*} value | |
| * @returns {string} | |
| */ | |
| export const getType = (value) => { | |
| const string = Object.prototype.toString.call(value) | |
| const [, type ] = /\[object (\w*)\]/.exec(string) | |
| return type | |
| } | |
| /** | |
| * Check if value's type is type (argument). | |
| * @param {*} value | |
| * @param {string} type | |
| * @returns {boolean} | |
| */ | |
| export const is = (value, type) => getType(value) === type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment