All files / object is-empty.ts

100% Statements 9/9
100% Branches 16/16
100% Functions 1/1
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29                        17x 2x   15x 2x   13x 3x   10x 4x   6x        
/**
 * Checks whether a container holds nothing: an empty string, array, `Map`, `Set` or object. `null` and
 * `undefined` count as empty.
 *
 * @param value - The value to check.
 * @returns `true` for an empty container, `null` or `undefined`; `false` for a number or a boolean.
 * @example
 * isEmpty({}); // true
 * isEmpty([0]); // false
 * isEmpty(new Map()); // true
 */
export function isEmpty(value: unknown): boolean {
  if (value === null || value === undefined) {
    return true;
  }
  if (typeof value === 'string') {
    return value.length === 0;
  }
  if (typeof value !== 'object') {
    return false;
  }
  if (value instanceof Map || value instanceof Set) {
    return value.size === 0;
  }
  return (
    (Array.isArray(value) || ArrayBuffer.isView(value) ? Reflect.get(value, 'length') : Object.keys(value).length) === 0
  );
}