UNPKG

@nent/core

Version:

Functional elements to add routing, data-binding, dynamic HTML, declarative actions, audio, video, and so much more. Supercharge static HTML files into web apps without script or builds.

102 lines (99 loc) 2.47 kB
/*! * NENT 2022 */ 'use strict'; /** * Throws an error if the value parameter is not defined. * @param {string} value the value that should not be null * @param {string} name the name of the parameter/variable to use in the error * @param {string|null} origin the name of the component/system throwing the error */ function requireValue(value, name, origin = null) { if (isNotValue(value)) { throw new Error(`${origin || 'nent'} : A value for ${name} was not provided.`); } } /** * Evaluate a value for existence. True if not null or undefined * @param {string} value * @returns {boolean} */ function isValue(value) { return isNotValue(value) === false; } /** * Evaluate a value for non-existence. True if null or undefined * @param {string} value * @returns {boolean} */ function isNotValue(value) { return value === undefined || value === null; } /** * Determines whether value is of type object * @param value * @returns true if object */ function isObject(value) { return isValue(value) && typeof value === 'object'; } /** * Determines whether value is of type string * @param value * @returns true if string */ function isString(value) { return typeof value === 'string'; } /** * Determines whether value is a serialized object * @param value * @returns true if string */ function isJson(value) { if (!isString(value)) return false; try { JSON.parse(value); } catch (e) { return false; } return true; } /** * Gets a property value from an object * (Like lodash get) * @param obj * @param key {string}|{string[]} * @param defaultValue * @returns property value */ function getPropertyValue(obj, key, defaultValue = null) { const travel = (regexp) => String.prototype.split .call(key, regexp) .filter(Boolean) .reduce((res, key) => res !== null && res !== undefined ? res[key] : res, obj); const result = travel(/[,\[\]]+?/) || travel(/[,\[\].]+?/); return result === undefined || result === obj ? defaultValue : result; } /** * Turn anything into an array. * * @param {any} any * * @returns {Array<any>} */ function valueToArray(any) { return any ? (Array.isArray(any) ? any : [any]) : []; } exports.getPropertyValue = getPropertyValue; exports.isJson = isJson; exports.isNotValue = isNotValue; exports.isObject = isObject; exports.isString = isString; exports.isValue = isValue; exports.requireValue = requireValue; exports.valueToArray = valueToArray;