UNPKG

es-toolkit

Version:

A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.

49 lines (48 loc) 1.85 kB
import { isBuffer } from "../../predicate/isBuffer.mjs"; import { isArrayLike } from "./isArrayLike.mjs"; import { isArguments } from "./isArguments.mjs"; import { isPrototype } from "../_internal/isPrototype.mjs"; import { isTypedArray } from "./isTypedArray.mjs"; //#region src/compat/predicate/isEmpty.ts /** * Checks if a given value is empty. * * - If the given value is a string, checks if it is an empty string. * - If the given value is an array, `Map`, or `Set`, checks if its size is 0. * - If the given value is an [array-like object](../predicate/isArrayLike.md), checks if its length is 0. * - If the given value is an object, checks if it is an empty object with no properties. * - Primitive values (booleans, numbers, or bigints) are considered empty. * * @param [value] - The value to check. * @returns `true` if the value is empty, `false` otherwise. * * @example * isEmpty(); // true * isEmpty(null); // true * isEmpty(""); // true * isEmpty([]); // true * isEmpty({}); // true * isEmpty(new Map()); // true * isEmpty(new Set()); // true * isEmpty("hello"); // false * isEmpty([1, 2, 3]); // false * isEmpty({ a: 1 }); // false * isEmpty(new Map([["key", "value"]])); // false * isEmpty(new Set([1, 2, 3])); // false */ function isEmpty(value) { if (value == null) return true; if (isArrayLike(value)) { if (typeof value.splice !== "function" && typeof value !== "string" && !isBuffer(value) && !isTypedArray(value) && !isArguments(value)) return false; return value.length === 0; } if (typeof value === "object" || typeof value === "function") { if (value instanceof Map || value instanceof Set) return value.size === 0; const keys = Object.keys(value); if (isPrototype(value)) return keys.filter((x) => x !== "constructor").length === 0; return keys.length === 0; } return true; } //#endregion export { isEmpty };