49 lines
1.8 KiB
JavaScript
49 lines
1.8 KiB
JavaScript
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 {unknown} [value] - The value to check.
|
|
* @returns {boolean} `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") {
|
|
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 };
|