-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray-identical.assert.ts
More file actions
49 lines (47 loc) · 1.4 KB
/
Copy patharray-identical.assert.ts
File metadata and controls
49 lines (47 loc) · 1.4 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
import { AssertionError } from "../../assertion-error.js";
import { desc } from "../../describe/describe.js";
/**
* Assert that an array holds the same members as the expected array, compared
* by identity, with type narrowing.
*
* The two arrays are compared by length and then member by member using
* Object.is, so a member that is itself an array or an object has to be the
* same reference on both sides. assertIdentical() compares a whole value with
* ===, and assertArrayEquals() compares members by value.
* @example
* ```ts
* import { assertArrayIdentical } from "@kensio/smartass";
*
* const admin = { name: "Ada" };
* const value: unknown = [admin];
*
* assertArrayIdentical(value, [admin]);
*
* // value is now narrowed to [{ name: string }]
* ```
*/
export function assertArrayIdentical<
const TExpected extends readonly unknown[],
>(
actual: unknown,
expected: TExpected,
message?: string,
): asserts actual is TExpected {
if (!Array.isArray(actual) || !arraysIdentical(actual, expected)) {
throw new AssertionError(
message ??
`Expected ${desc(actual)} to be identical to ${desc(expected)}.`,
actual,
expected,
);
}
}
function arraysIdentical(
actual: readonly unknown[],
expected: readonly unknown[],
): boolean {
return (
actual.length === expected.length &&
actual.every((element, index) => Object.is(element, expected[index]))
);
}