-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-length.assert.ts
More file actions
54 lines (48 loc) · 1.55 KB
/
Copy patharray-length.assert.ts
File metadata and controls
54 lines (48 loc) · 1.55 KB
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
import { arrayOfLength } from "./array-length.match.js";
import { AssertionError } from "../../assertion-error.js";
import { desc, repr } from "../../describe/describe.js";
import type { ArrayOfLength, ArrayOfLengthMatch } from "./array-length.type.js";
export function assertArrayLength<
TArray extends unknown[] | null | undefined,
const N extends number,
>(
value: TArray,
expectedLength: N,
message?: string,
): asserts value is Extract<NonNullable<TArray>, unknown[]> &
ArrayOfLengthMatch<TArray, N>;
export function assertArrayLength<const N extends number>(
value: unknown,
expectedLength: N,
message?: string,
): asserts value is ArrayOfLength<unknown, N>;
/**
* Assert that an array has exactly the expected length, with type narrowing.
* The type narrowing indicates:
* - An empty array for 0
* - An exact number of elements up to 10
* - At least 10 elements for >10
*/
export function assertArrayLength(
value: unknown,
expectedLength: number,
message?: string,
): void {
const matcher = arrayOfLength(expectedLength);
if (!matcher.matches(value)) {
throw new AssertionError(
message ?? buildArrayLengthMessage(value, expectedLength),
value,
matcher.represent(),
);
}
}
function buildArrayLengthMessage(
value: unknown,
expectedLength: number,
): string {
if (!Array.isArray(value)) {
return `Expected ${desc(value)} to be an array of length ${repr(expectedLength)}.`;
}
return `Expected ${desc(value)} to have length ${repr(expectedLength)}, but it had length ${repr(value.length)}.`;
}