-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-min-length.assert.ts
More file actions
64 lines (58 loc) · 1.85 KB
/
Copy patharray-min-length.assert.ts
File metadata and controls
64 lines (58 loc) · 1.85 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
55
56
57
58
59
60
61
62
63
64
import { arrayOfMinLength } from "./array-min-length.match.js";
import { AssertionError } from "../../assertion-error.js";
import { desc, repr } from "../../describe/describe.js";
import type {
ArrayOfMinLength,
ArrayOfMinLengthMatch,
} from "./array-min-length.type.js";
export function assertArrayMinLength<
TActual extends object | null | undefined,
const N extends number,
>(
value: TActual,
minLength: N,
message?: string,
): asserts value is Extract<NonNullable<TActual>, readonly unknown[]> &
ArrayOfMinLengthMatch<Extract<NonNullable<TActual>, readonly unknown[]>, N>;
export function assertArrayMinLength<const N extends number>(
value: unknown,
minLength: N,
message?: string,
): asserts value is ArrayOfMinLength<unknown, N>;
/**
* Assert that an array has at least the expected minimum length, with type narrowing.
* The type narrowing indicates:
* - A non-empty array for 1
* - At least N elements up to 5
* - At least 5 elements for >5
* @example
* ```ts
* import { assertArrayMinLength } from "@kensio/smartass";
*
* const value: unknown = ["admin", "editor"];
*
* assertArrayMinLength(value, 2);
*
* // value is now narrowed to an array with at least 2 elements
* ```
*/
export function assertArrayMinLength(
value: unknown,
minLength: number,
message?: string,
): void {
const matcher = arrayOfMinLength(minLength);
if (!matcher.matches(value)) {
throw new AssertionError(
message ?? buildArrayMinLengthMessage(value, minLength),
value,
matcher.represent(),
);
}
}
function buildArrayMinLengthMessage(value: unknown, minLength: number): string {
if (!Array.isArray(value)) {
return `Expected ${desc(value)} to be an array of at least ${repr(minLength)} elements.`;
}
return `Expected ${desc(value)} to have at least ${repr(minLength)} elements, but it had ${repr(value.length)}.`;
}