All files / enum is-enum-value.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

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      2x                               21x 21x 6x 6x   21x    
import type { EnumObject } from './enum-object';
import { getEnumValues } from './get-enum-values';
 
const valuesByEnum = new WeakMap<object, ReadonlySet<unknown>>();
 
/**
 * Checks whether a value is one of the values of an enum, in O(1): the values of each enum are read once.
 *
 * @template E - The type of the enum object.
 * @param enumObject - The enum to search, such as `Direction`.
 * @param value - The value to look for.
 * @returns `true` when the value is one of the enum's values.
 * @cached The values of each enum, in a `WeakMap`: nothing is kept once the enum is unused.
 * @example
 * enum Direction { Up, Down }
 * isEnumValue(Direction, 0); // true
 * isEnumValue(Direction, 'Up'); // false (a name, not a value)
 */
export function isEnumValue<E extends EnumObject>(enumObject: E, value: unknown): value is E[keyof E] {
  let values = valuesByEnum.get(enumObject);
  if (!values) {
    values = new Set(getEnumValues(enumObject));
    valuesByEnum.set(enumObject, values);
  }
  return values.has(value);
}