UNPKG

is-explicit

Version:

Combines instance of operator and typeof operator in a way that works seamlessly with objects and literals.

59 lines (42 loc) 2.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.typeIsValid = typeIsValid; exports.default = void 0; var _isInstanceable = _interopRequireDefault(require("./is-instanceable")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This is a pain in the ass, but without it the babel transpile breaks Symbol // checking, because Symbol !== require('babel-runtime/core-js/symbol') /******************************************************************************/ // Helper /******************************************************************************/ const TESTS = { string: type => type === String, boolean: type => type === Boolean, number: (type, value) => type === Number && !Number.isNaN(value), symbol: type => type === Symbol, function: (type, value) => type === Function, object: (type, value) => type === Object ? value !== null : type === Array ? Array.isArray(value) : value instanceof type, undefined: type => false }; function typeIsValid(type, isArray = Array.isArray(type)) { return isArray ? type.length > 0 && type.every(_isInstanceable.default) : (0, _isInstanceable.default)(type); } /******************************************************************************/ // Main /******************************************************************************/ function is(value, type) { type = this || type; const typesAsArray = Array.isArray(type); // Validate type arguments if (!typeIsValid(type, typesAsArray)) throw new Error(`${typesAsArray ? 'types' : 'type'} ` + `${typesAsArray ? 'are' : 'is'} expected to be ` + `${typesAsArray ? 'an array of' : 'a'} prototypal ` + `${typesAsArray ? 'functions' : 'function'}`); // Test types const test = TESTS[typeof value]; if (!typesAsArray) return test(type, value); for (const t of type) if (test(t, value)) return true; return false; } /******************************************************************************/ // Exports /******************************************************************************/ var _default = is; exports.default = _default;