Skip to content

Instantly share code, notes, and snippets.

@TheFoot
Last active March 15, 2021 15:33
Show Gist options
  • Save TheFoot/ae00eb0812b766fcbe1c30c897b2ee65 to your computer and use it in GitHub Desktop.
Save TheFoot/ae00eb0812b766fcbe1c30c897b2ee65 to your computer and use it in GitHub Desktop.
/**
* This module provides native variable type checking utilities
* It has no external dependencies
* Single-line functions used for conciseness
* No parsing or coercion is performed
*/
const TypeUtils = {
// Strings
isString: value => typeof value === 'string',
// Number
isNumber: value => !isNaN ( value ) && typeof value === 'number',
// Integer
isInteger: value => parseInt ( value, 10 ) === value,
// Float
isFloat: value => ('' + value).includes ( '.' ) && parseFloat ( value ) === value,
// Infinite
isInfinite: value => value === Infinity,
// Boolean
isBoolean: value => [ false, true ].includes ( value ),
// Object
isObject: value => typeof value === 'object' && !Array.isArray ( value ),
// Array
isArray: value => Array.isArray ( value ),
// Array-like - Array, Set, Map
isArrayLike: value => value instanceof Set || value instanceof Map || Array.isArray ( value ),
// Function
isFunction: value => typeof value === 'function',
// Null
isNull: value => value === null,
// Undefined
isUndefined: value => value === undefined,
// Null or undefined
isNullOrUndefined: value => [ null, undefined ].includes ( value ),
// Empty
// Numbers, Booleans aren't ever considered "empty"
isEmpty: value => {
// Null / Undefined
if ( TypeUtils.isNull ( value ) || TypeUtils.isUndefined ( value ) ) {
return true;
}
// String
if ( TypeUtils.isString ( value ) && value.length === 0 ) {
return true;
}
// Arrays
if ( TypeUtils.isArray ( value ) ) {
return value.length === 0;
}
// Sets, Maps
if ( TypeUtils.isArrayLike ( value ) ) {
return value.size === 0;
}
// Objects
if ( TypeUtils.isObject ( value ) && Object.keys ( value ).length === 0 ) {
return true;
}
return false;
},
// Date
isDate: value => {
return (
!TypeUtils.isNullOrUndefined ( value )
&& value.constructor === Date
&& TypeUtils.isInteger ( value.getTime () )
);
},
// Promise
isPromise: value => Boolean ( value && TypeUtils.isFunction ( value.then ) )
};
module.exports = TypeUtils;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment