@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
86 lines (85 loc) • 2.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._isFalsy = exports._isTruthy = exports._isNotNullish = exports._isNullish = exports._isUndefined = exports._isNull = void 0;
exports._isObject = _isObject;
exports._isPrimitive = _isPrimitive;
exports._isEmptyObject = _isEmptyObject;
exports._isNotEmptyObject = _isNotEmptyObject;
exports._isEmpty = _isEmpty;
exports._isNotEmpty = _isNotEmpty;
const _isNull = (v) => v === null;
exports._isNull = _isNull;
const _isUndefined = (v) => v === undefined;
exports._isUndefined = _isUndefined;
const _isNullish = (v) => v === undefined || v === null;
exports._isNullish = _isNullish;
const _isNotNullish = (v) => v !== undefined && v !== null;
exports._isNotNullish = _isNotNullish;
/**
* Same as Boolean, but with correct type output.
* Related:
* https://github.com/microsoft/TypeScript/issues/16655
* https://www.karltarvas.com/2021/03/11/typescript-array-filter-boolean.html
*
* @example
*
* [1, 2, undefined].filter(_isTruthy)
* // => [1, 2]
*/
const _isTruthy = (v) => !!v;
exports._isTruthy = _isTruthy;
const _isFalsy = (v) => !v;
exports._isFalsy = _isFalsy;
/**
* Returns true if item is Object, not null and not Array.
*
* Currently treats RegEx as Object too, e.g _isObject(/some/) === true
*/
function _isObject(obj) {
return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) || false;
}
function _isPrimitive(v) {
return (v === null ||
v === undefined ||
typeof v === 'number' ||
typeof v === 'boolean' ||
typeof v === 'string' ||
typeof v === 'bigint' ||
typeof v === 'symbol');
}
function _isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
function _isNotEmptyObject(obj) {
return Object.keys(obj).length > 0;
}
/**
* Object is considered empty if it's one of:
* undefined
* null
* '' (empty string)
* [] (empty array)
* {} (empty object)
* new Map() (empty Map)
* new Set() (empty Set)
*/
function _isEmpty(obj) {
if (obj === undefined || obj === null)
return true;
if (typeof obj === 'string' || Array.isArray(obj)) {
return obj.length === 0;
}
if (obj instanceof Map || obj instanceof Set) {
return obj.size === 0;
}
if (typeof obj === 'object') {
return Object.keys(obj).length === 0;
}
return false;
}
/**
* @see _isEmpty
*/
function _isNotEmpty(obj) {
return !_isEmpty(obj);
}