-
Notifications
You must be signed in to change notification settings - Fork 51
/
list.ts
44 lines (42 loc) · 1.12 KB
/
list.ts
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
export class Cons<A> {
constructor(public value: A, public next: Cons<A> | undefined) {}
toArray(): A[] {
const array = [];
let cur: Cons<A> | undefined = this;
while (cur !== undefined) {
array.push(cur.value);
cur = cur.next;
}
return array;
}
nth(index: number): A | undefined {
let cur: Cons<A> | undefined = this;
for (let i = 0; i < index && cur !== undefined; ++i) {
cur = cur.next;
}
return cur === undefined ? undefined : cur.value;
}
}
export function copyFirst<A>(n: number, list: Cons<A>): Cons<A> {
const newHead = new Cons(list.value, undefined);
let current = list;
let newCurrent = newHead;
while (--n > 0) {
current = current.next!;
const cons = new Cons(current.value, undefined);
newCurrent.next = cons;
newCurrent = cons;
}
return newHead;
}
export function concat<A>(a: Cons<A>, b: Cons<A>): Cons<A> {
let list = new Cons(a.value, undefined);
let prev = list;
let cur = a;
while ((cur = cur.next!) !== undefined) {
prev.next = new Cons(cur.value, undefined);
prev = prev.next;
}
prev.next = b;
return list;
}