-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathList.ts
119 lines (101 loc) · 2.44 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* List class implement
*/
import { compare } from "./util";
export class List<T> {
private listSize: number;
private pos: number;
private dataStore: T[];
constructor() {
this.dataStore = new Array<T>();
this.listSize = 0;
this.pos = 0;
}
// add one element
public append(elem: T) {
this.dataStore[this.listSize++] = elem;
}
// find an element
// return the elem's index in the list
public find(elem: T): number {
for (let i = 0; i < this.listSize; i++) {
if (compare(this.dataStore[i], elem)) {
return i;
}
}
return -1;
}
// remove an element
public remove(elem: T): boolean {
let foundAt = this.find(elem);
if (foundAt > -1) {
this.dataStore.splice(foundAt, 1);
--this.listSize;
return true;
}
return false;
}
// insert one element after the pos in the list
public insert(elem: T, after: T): boolean {
let insPos = this.find(after);
if (insPos > -1) {
this.dataStore.splice(insPos + 1, 0, elem);
this.listSize++;
return true;
}
return false;
}
// clear the list
public clear() {
delete this.dataStore;
this.dataStore = new Array<T>();
this.listSize = this.pos = 0;
}
// check if list contain element
public contains(elem: T): boolean {
for (let i = 0; i < this.listSize; i++) {
if (compare(this.dataStore[i], elem)) {
return true;
}
}
return false;
}
public front() {
this.pos = 0;
}
public end() {
this.pos = this.listSize - 1;
}
public prev() {
if (this.pos > 0) {
--this.pos;
}
}
public next() {
if (this.pos < this.listSize) {
this.pos++;
}
}
public curPos(): number {
return this.pos;
}
public moveTo(pos: number) {
if (pos < 0) {
this.pos = 0;
} else if (pos > this.listSize - 1) {
this.pos = this.listSize - 1;
} else {
this.pos = pos;
}
}
public getElement(): T {
return this.dataStore[this.pos];
}
// length
public length(): number {
return this.listSize;
}
public toString() {
return this.dataStore;
}
}