aboutsummaryrefslogtreecommitdiff
path: root/scripts/apidocs/utils/value-checks.ts
blob: f8578ccc311d56d4c22fec189ee9da4eba50e2ca (plain)
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
60
61
62
63
64
65
66
67
68
69
export function exactlyOne<T>(input: ReadonlyArray<T>, property: string): T {
  if (input.length !== 1) {
    throw new Error(
      `Expected exactly one element for ${property}, got ${input.length}`
    );
  }

  return input[0];
}

export function optionalOne<T>(
  input: ReadonlyArray<T>,
  property: string
): T | undefined {
  if (input.length > 1) {
    throw new Error(
      `Expected one optional element for ${property}, got ${input.length}`
    );
  }

  return input[0];
}

export function required<T>(
  input: T | undefined,
  property: string
): NonNullable<T> {
  if (input == null) {
    throw new Error(`Expected a value for ${property}, got undefined`);
  }

  return input;
}

export function allRequired<T>(
  input: ReadonlyArray<T | undefined>,
  property: string
): Array<NonNullable<T>> {
  return input.map((v, i) => required(v, `${property}[${i}]`));
}

export function atLeastOne<T>(
  input: ReadonlyArray<T>,
  property: string
): ReadonlyArray<T> {
  if (input.length === 0) {
    throw new Error(`Expected at least one element for ${property}`);
  }

  return input;
}

export function atLeastOneAndAllRequired<T>(
  input: ReadonlyArray<T | undefined>,
  property: string
): ReadonlyArray<NonNullable<T>> {
  return atLeastOne(allRequired(input, property), property);
}

export function valueForKey<T>(input: Record<string, T>, key: string): T {
  return required(input[key], key);
}

export function valuesForKeys<T>(
  input: Record<string, T>,
  keys: string[]
): T[] {
  return keys.map((key) => valueForKey(input, key));
}