@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
71 lines (70 loc) • 1.92 kB
JavaScript
export const _isNull = (v) => v === null;
export const _isUndefined = (v) => v === undefined;
export const _isNullish = (v) => v === undefined || v === null;
export const _isNotNullish = (v) => v !== undefined && v !== null;
/**
* 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]
*/
export const _isTruthy = (v) => !!v;
export const _isFalsy = (v) => !v;
/**
* Returns true if item is Object, not null and not Array.
*
* Currently treats RegEx as Object too, e.g _isObject(/some/) === true
*/
export function _isObject(obj) {
return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) || false;
}
export function _isPrimitive(v) {
return (v === null ||
v === undefined ||
typeof v === 'number' ||
typeof v === 'boolean' ||
typeof v === 'string' ||
typeof v === 'bigint' ||
typeof v === 'symbol');
}
export function _isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
export 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)
*/
export 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
*/
export function _isNotEmpty(obj) {
return !_isEmpty(obj);
}