isEmpty
The isEmpty utility checks if a given value is considered "empty". It supports a wide variety of data types, including strings, arrays, objects, Maps, and Sets.
Implementation
View Source Code
ts
import { isArray } from './isArray';
import { isNil } from './isNil';
import { isObject } from './isObject';
/**
* Checks if the given argument is empty.
*
* @example
* ```ts
* isEmpty(null); // true
* isEmpty(undefined); // true
* isEmpty([]); // true
* isEmpty({}); // true
* isEmpty(''); // true
* isEmpty(0); // false
* isEmpty(123); // false
* isEmpty('abc'); // false
* isEmpty([1, 2, 3]); // false
* isEmpty({ a: 1, b: 2 }); // false
* ```
*
* @param arg - The argument to be checked.
*
* @returns `true` if all arguments are `null`, `undefined`, `{}`, `[]`, or empty strings. Otherwise, it returns `false`.
*/
// biome-ignore lint/suspicious/noExplicitAny: -
export function isEmpty(arg: any): boolean {
if (isNil(arg) || arg === '') return true;
if (isArray(arg)) return arg.length === 0;
if (arg instanceof Map || arg instanceof Set) return arg.size === 0;
if (isObject(arg)) return Object.keys(arg).length === 0;
return false;
}
export const IS_EMPTY_ERROR_MSG = 'Expected an empty value';Features
- Isomorphic: Works in both Browser and Node.js.
- Versatile: Handles strings (length 0), arrays (length 0), objects (no enumerable keys), and collection types (size 0).
- Safe: Properly handles
nullandundefined(considering them empty).
API
ts
function isEmpty(value: unknown): boolean;Parameters
value: The value to check for emptiness.
Returns
trueif the value is empty; otherwise,false.
Examples
Checking Collections
ts
import { isEmpty } from '@vielzeug/toolkit';
isEmpty([]); // true
isEmpty([1, 2, 3]); // false
isEmpty(new Set()); // true
isEmpty(new Map()); // trueChecking Strings & Objects
ts
import { isEmpty } from '@vielzeug/toolkit';
isEmpty(''); // true
isEmpty('hello'); // false
isEmpty({}); // true
isEmpty({ a: 1 }); // falseChecking Nullable Values
ts
import { isEmpty } from '@vielzeug/toolkit';
isEmpty(null); // true
isEmpty(undefined); // trueImplementation Notes
- For objects, it checks for own enumerable property names using
Object.keys(). - For
MapandSet, they are treated as objects. An empty Map or Set will returntruesinceObject.keys()returns an empty array for them. - For all other types (numbers, booleans, etc.), it returns
falseunless the value isnullorundefined.