-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-includes-all.assert.ts
More file actions
83 lines (72 loc) · 2.26 KB
/
Copy patharray-includes-all.assert.ts
File metadata and controls
83 lines (72 loc) · 2.26 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { arrayIncludingAll } from "./array-includes-all.match.js";
import { AssertionError } from "../../assertion-error.js";
import { desc, repr } from "../../describe/describe.js";
import type {
ArrayElement,
ArrayIncludingAll,
ArrayIncludingAllElement,
} from "./array-includes-all.type.js";
export function assertArrayIncludesAll<
TArray extends unknown[],
const E extends readonly ArrayElement<TArray>[],
>(
value: TArray,
elements: E,
message?: string,
): asserts value is TArray &
ArrayIncludingAll<ArrayElement<TArray>, E["length"]>;
export function assertArrayIncludesAll<const E extends readonly unknown[]>(
value: unknown,
elements: E,
message?: string,
): asserts value is ArrayIncludingAll<ArrayIncludingAllElement<E>, E["length"]>;
/**
* Assert that an array includes all specified elements, with type narrowing.
* Elements can appear in any order and do not need to be contiguous.
* Repeated required elements must appear at least that many times.
*/
export function assertArrayIncludesAll(
value: unknown,
elements: readonly unknown[],
message?: string,
): void {
const matcher = arrayIncludingAll(elements);
if (!matcher.matches(value)) {
throw new AssertionError(
message ?? buildArrayIncludesAllMessage(value, elements),
value,
matcher.represent(),
);
}
}
function buildArrayIncludesAllMessage(
value: unknown,
elements: readonly unknown[],
): string {
if (!Array.isArray(value)) {
return `Expected ${desc(value)} to be array including all of ${desc(elements)}.`;
}
const missing = findMissingElements(value, elements);
return `Expected ${desc(value)} to include all of ${repr(elements)}, but missing ${repr(missing)}.`;
}
function findMissingElements(
value: readonly unknown[],
elements: readonly unknown[],
): unknown[] {
const remaining = [...value];
const missing: unknown[] = [];
for (const element of elements) {
const index = remaining.findIndex((candidate) =>
sameValueZero(candidate, element),
);
if (index === -1) {
missing.push(element);
} else {
remaining.splice(index, 1);
}
}
return missing;
}
function sameValueZero(left: unknown, right: unknown): boolean {
return left === right || (Number.isNaN(left) && Number.isNaN(right));
}