Commit 0a956494 authored by Milan Wikarski's avatar Milan Wikarski
Browse files

Initial commit

parents
node_modules
module.exports = require('./src/js-type');
{
"name": "js-type",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git@gitlab.creanet.sk:npm-packages/js-type.git"
},
"keywords": [],
"author": "",
"license": "ISC"
}
/**
* Returns `true` if val is a string; `false` otherwise
*
* @param {*} val
* @returns {boolean}
*/
function isString(val) {
return typeof val == 'string';
}
/**
* Returns `true` if val is an array; `false` otherwise
*
* @param {*} val
* @returns {boolean}
*/
function isArray(val) {
return Array.isArray(val);
}
/**
* Returns `true` if val is numeric; `false` otherwise
*
* @param {*} val
* @returns {boolean}
*/
function isNumeric(val) {
return !isNaN(Number(val));
}
/**
* Returns `true` is val is instanceof prototype
*
* @param {*} val
* @param {*} prototype
* @returns {Boolean}
*/
function isInstance(val, prototype) {
return val instanceof prototype;
}
/**
* Returns `true` is val is Object; `false` otherwise
*
* @param {*} val
* @returns {Boolean}
*/
function isObject(val) {
return isInstance(val, Object);
}
/**
* Returns `true` if val is null; `false` otherwise
*
* @param {*} val
* @returns {Boolean}
*/
function isNull(val) {
return val == null;
}
/**
* Returns `true` if value is undefined; `false` otherwise
*
* @param {*} val
* @returns {Boolean}
*/
function isUndefined(val) {
return val === undefined;
}
/**
* Returns `true` is value is a function; `false` otherwise
*
* @param {*} val
* @returns {Boolean}
*/
function isFunction(val) {
return isInstance(val, Function);
}
const _is = {
string: isString,
array: isArray,
numeric: isNumeric,
instance: isInstance,
object: isObject,
null: isNull,
undefined: isUndefined,
function: isFunction
};
/**
* Checks if value is of one of valid types specified by `types` array.
* valid items in `types` are:
* - `{string}`: type name (eg. 'numeric') - checks type
* - `{Object}`: instance (eg. Regex) - checks instanceof
*
* @param {*} val
* @param {Array.<string|Object>} types
* @returns
*/
function is(val, types) {
if (!_is.array(types)) throw TypeError('Types is not an array');
for (let i = 0; i < types.length; i++) {
const type = types[i];
if (isString(type)) {
if (_is[type](val)) {
return true;
}
} else if (isObject(type)) {
if (isInstance(val, type)) {
return true;
}
}
}
return false;
}
is.string = isString;
is.array = isArray;
is.numeric = isNumeric;
is.instance = isInstance;
is.object = isObject;
is.null = isNull;
is.undefined = isUndefined;
is.function = isFunction;
module.exports = is;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment