Skip to content

Commit a5f766e

Browse files
committed
✅ List tests
1 parent 7cd7b25 commit a5f766e

File tree

2 files changed

+64
-5
lines changed

2 files changed

+64
-5
lines changed

src/language/list.test.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { assertEquals, assertThrows } from "../../deps.ts";
2+
import {
3+
arrayToList,
4+
arrayToListFor,
5+
arrayToListReduce,
6+
nth,
7+
prepend,
8+
} from "./list.ts";
9+
10+
const EXAMPLE_LIST = {
11+
value: 1,
12+
rest: {
13+
value: 2,
14+
rest: {
15+
value: 3,
16+
rest: null,
17+
},
18+
},
19+
};
20+
21+
Deno.test("[arrayToList]", () => {
22+
assertEquals(arrayToList([1, 2, 3]), EXAMPLE_LIST);
23+
});
24+
25+
Deno.test("[arrayToListFor]", () => {
26+
assertEquals(arrayToListFor([1, 2, 3]), EXAMPLE_LIST);
27+
});
28+
29+
Deno.test("[arrayToListReduce]", () => {
30+
assertEquals(arrayToListReduce([1, 2, 3]), EXAMPLE_LIST);
31+
});
32+
33+
Deno.test("[nth]", () => {
34+
const nth3 = nth(EXAMPLE_LIST, 2);
35+
assertEquals(nth3, 3);
36+
37+
assertThrows(
38+
() => {
39+
nth(EXAMPLE_LIST, 5);
40+
},
41+
RangeError,
42+
"Index out of range",
43+
);
44+
});
45+
46+
Deno.test("[prepend]", () => {
47+
const prepended = prepend(4, EXAMPLE_LIST);
48+
49+
assertEquals(prepended, {
50+
value: 4,
51+
rest: EXAMPLE_LIST,
52+
});
53+
});

src/language/list.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ export function arrayToListReduce<T>(values: T[]) {
1616
}
1717

1818
export function arrayToListFor<T>(values: T[]) {
19-
let rest = {};
19+
let rest: List<T> | null = null;
2020

21-
for (let i = values.length - 1; i >= 0; i--) {
22-
rest = { value: values[i], rest };
21+
const reversedItems = values.reverse();
22+
23+
for (const value of reversedItems) {
24+
rest = { value, rest };
2325
}
2426

25-
return rest as List<T>;
27+
return rest;
2628
}
2729

2830
export function prepend<T>(value: T, rest: List<T>): List<T> {
@@ -34,5 +36,9 @@ export function nth<T>(list: List<T>, index: number): T {
3436
return list.value;
3537
}
3638

37-
return nth(list.rest!, index - 1);
39+
if (list.rest === null) {
40+
throw new RangeError("Index out of range.");
41+
}
42+
43+
return nth(list.rest, index - 1);
3844
}

0 commit comments

Comments
 (0)