All files / data/src/model enum.ts

100% Statements 59/59
83.33% Branches 5/6
100% Functions 3/3
100% Lines 59/59

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 4x 4x 4x 4x 2x 2x 2x  
/**
 * Abstract **Enum** helper class. This class is used by the {@link Model} to
 * detect **Enum**erations within a {@link Model.Graph}, as **Enum**erations (in
 * contrast to plain strings) must not be quoted. This class should never be
 * instantiated manually, but instead is used internally by the
 * {@link enumerate} function.
 *
 * @see {@link enumerate}
 */
export abstract class Enum extends String {
 
  /**
   * Private **constructor** (which should never be called).
   *
   * @throws A {@link TypeError} upon construction.
   */
  // @ts-expect-error missing super call
  private constructor() {
    throw new TypeError('Enum.constructor');
  }
 
}
 
/**
 * **enumerate** helper function. Enumerations are special objects and all used
 * TypeScript `enum`s have to be looped through this helper function before they
 * can be utilized in conjunction with the {@link Model}.
 *
 * @param enumerator - The TypeScript `enum` to **enumerate**.
 * @typeParam T - The type of TypeScript `enum`.
 * @returns The processed enumeration to be used by the {@link Model}.
 *
 * @example
 * **enumerate** a TypeScript enumeration:
 * ```ts
 * import { enumerate } from '@sgrud/data';
 *
 * enum Enumeration {
 *   One = 'ONE',
 *   Two = 'TWO'
 * }
 *
 * export type ExampleEnum = Enumeration;
 * export const ExampleEnum = enumerate(Enumeration);
 * ```
 *
 * @see {@link Model}
 */
export function enumerate<T extends object>(enumerator: T): T {
  const enumeration = {} as Record<string, Enum>;
 
  for (const key in enumerator) {
    const value = new String(enumerator[key]);
    Object.setPrototypeOf(value, Enum.prototype);
    enumeration[key] = value;
  }
 
  return enumeration as T;
}