-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Vector.ts
425 lines (370 loc) · 10.8 KB
/
Vector.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import { DEFAULT_VECTOR_ALLOC_STEP, DEFAULT_VECTOR_CAPACITY } from "./constants";
import { Sequence } from "./interfaces";
import { CursorBase, isIterable, RangeBase } from "./util";
export class VectorCursor<T> extends CursorBase<T> {
constructor(public vector: Vector<T>, public _index: number) {
super();
}
public get value() {
return this.vector._elements[this._index];
}
public set value(newValue: T) {
this.vector._elements[this._index] = newValue;
}
public *[Symbol.iterator]() {
const elements = this.vector._elements;
const size = this.vector._elementCount;
for (let i = this._index; i < size; ++i) {
yield elements[i];
}
}
public next() {
if (this._index === this.vector._elementCount - 1) {
return null;
}
return new VectorCursor<T>(this.vector, this._index + 1);
}
public prev() {
if (this._index === 0) {
return null;
}
return new VectorCursor<T>(this.vector, this._index - 1);
}
}
/**
* @ignore
*/
export class VectorRange<T> extends RangeBase<T> {
constructor(public _vector: Vector<T>, public _min: number, public _max: number, public readonly reversed: boolean) {
super();
}
get size() {
return this._max - this._min;
}
public slice(a: number, b: number) {
return new VectorRange<T>(this._vector, this._min + a, this._min + b, this.reversed);
}
public *[Symbol.iterator]() {
if (!this.reversed) {
for (let i = this._min; i < this._max; ++i) {
yield this._vector._elements[i];
}
} else {
for (let i = this._max; i >= this._min; i--) {
yield this._vector._elements[i];
}
}
}
public *cursors() {
if (this.reversed) {
for (let i = this._max; i >= this._min; i--) {
yield new VectorCursor<T>(this._vector, i);
}
} else {
for (let i = this._min; i < this._max; ++i) {
yield new VectorCursor<T>(this._vector, i);
}
}
}
public reverse() {
return new VectorRange<T>(this._vector, this._min, this._max, !this.reversed);
}
}
function copy<T>(
src: T[],
dst: T[],
dstStart = 0,
srcStart = 0,
srcEnd: number = src.length,
) {
for (let i = 0; i < srcEnd - srcStart; i++) {
dst[dstStart + i] = src[srcStart + i];
}
}
function createArray<T>(iterable: Iterable<T>, capacity: number) {
const elements = [...iterable];
const size = elements.length;
elements.length = Math.max(size, capacity);
return [elements, size] as [T[], number];
}
/**
* Options to be passed to the constructor of [[Vector]].
*
* You don't have to specify these values, as the vector implementation will
* attempt to load sane defaults.
*
* @see [[Vector.constructor]]
*/
export interface VectorOptions<T> {
/**
* An iterable that will be consumed to fill the vector.
*/
elements?: Iterable<T>;
/**
* This value specifies how much capacity the vector should _at least_ have.
*/
capacity?: number;
/**
* When the vector overflows, this option determines how big the vector will
* become.
*/
allocStep?: number;
}
/**
* A vector is a sequence with fast member access by sequence number.
*
* ```
* import { Vector } from "scl"
* ```
*
* Inserting elements anywhere else than at the end is very slow and should be
* avoided. When inserting, the vector may need to re-allocate to provide
* enough room for the new element.
*
* The following table summarises the time complexity of the most commonly used
* properties.
*
* | Property name | Worst-case |
* |--------------------------------------------|------------|
* | {@link Vector.append append()} | O(n) |
* | {@link Vector.at at()} | O(1) |
* | {@link Vector.at getAt()} | O(1) |
* | {@link Vector.insertAfter insertAfter()} | O(n) |
* | {@link Vector.insertBefore insertBefore()} | O(n) |
* | {@link Vector.deleteAt deleteAt()} | O(n) |
* | {@link Vector.prepend prepend()} | O(n) |
* | {@link Vector.size size} | O(1) |
*
* ```ts
* const v = new Vector<number>()
* v.append(1)
* v.append(2)
* v.append(3)
* assert.strictEqual(v.size, 3)
* ```
*
* @see [[DoubleLinkedList]]
* @see [[SingleLinkedList]]
*
* @typeparam T The type of element in the collection.
*/
export class Vector<T> implements Sequence<T> {
/**
* @ignore
*/
public _elements: T[];
/**
* @ignore
*/
public _elementCount: number;
/**
* @ignore
*/
public _allocStep: number;
/**
* Construct a new vector.
*
* ```ts
* const v1 = new Vector<number>([1, 2, 3, 4, 5])
* assert.strictEqual(v.size, 5)
* ```
*
* ```ts
* const v2 = new Vector<number>({ capacity: 1024 })
* for (let i = 0; i < 1024; i++) {
* v2.append(i)
* }
* ```
*
* @param iter Any iterable, of which the elements will be copied to this vector.
* @param opts Additional options to customize the newly created vector.
*/
constructor(opts: Iterable<T> | VectorOptions<T> = {}) {
if (isIterable(opts)) {
const [elements, size] = createArray(opts, DEFAULT_VECTOR_CAPACITY);
this._elements = elements;
this._elementCount = size;
this._allocStep = DEFAULT_VECTOR_ALLOC_STEP;
} else {
const capacity = opts.capacity !== undefined ? opts.capacity : DEFAULT_VECTOR_CAPACITY;
this._allocStep = opts.allocStep !== undefined ? opts.allocStep : DEFAULT_VECTOR_ALLOC_STEP;
if (opts.elements !== undefined) {
const [elements, size] = createArray(opts.elements, capacity);
this._elementCount = size;
this._elements = elements;
} else {
this._elementCount = 0;
this._elements = new Array(capacity);
}
}
}
/**
* Get how much elements this vector can hold before it needs to re-allocate.
*
* @see [[Vector.size]]
*/
public get capacity(): number {
return this._elements.length;
}
/**
* Ensure the vector can store at least `count` amount of elements.
*
* The [[size]] property of this vector is never changed during this call.
*/
public allocate(count: number): void {
this._elements.length = Math.max(this._elements.length, count);
// if (count <= this._elements.length) {
// return;
// }
// const newElements = new Array(count);
// copy(this._elements, newElements, 0, this._elementCount);
// this._elements = newElements;
}
public has(element: T): boolean {
for (let i = 0; i < this._elementCount; i++) {
if (this._elements[i] === element) {
return true;
}
}
return false;
}
public replace(index: number, element: T): void {
if (index < 0 || index >= this._elementCount) {
throw new RangeError(`Could not replace element: index ${index} out of bounds.`);
}
this._elements[index] = element;
}
public getAt(index: number) {
if (index < 0 || index >= this._elementCount) {
throw new RangeError(`Could not get element: index ${index} out of bounds.`);
}
return this._elements[index];
}
public shrinkFit() {
this._elements.length = this._elementCount;
}
/**
* Get how many elements are actually in the container.
*
* @see [[capacity]]
*/
public get size(): number {
return this._elementCount;
}
public insertAfter(pos: VectorCursor<T>, element: T) {
if (this._elements.length === this._elementCount) {
this._elements.length += this._allocStep;
}
this._elements.copyWithin(pos._index + 2, pos._index + 1, this._elementCount);
this._elementCount++;
this._elements[pos._index + 1] = element;
return new VectorCursor<T>(this, pos._index + 1);
}
public insertBefore(pos: VectorCursor<T>, element: T) {
if (this._elements.length === this._elementCount) {
this._elements.length += this._allocStep;
}
this._elements.copyWithin(pos._index + 1, pos._index, this._elementCount);
this._elements[pos._index] = element;
this._elementCount++;
return new VectorCursor<T>(this, pos._index);
}
public slice(a: number, b: number) {
return new VectorRange<T>(this, a, b, false);
}
public first(): T {
if (this._elementCount === 0) {
throw new Error(`Could not get first element: collection is empty.`);
}
return this._elements[0];
}
public last(): T {
if (this._elementCount === 0) {
throw new Error(`Could not get last element: collection is empty.`);
}
return this._elements[this._elementCount - 1];
}
public toRange() {
return new VectorRange<T>(this, 0, this._elementCount, false);
}
public prepend(el: T) {
if (this._elements.length === this._elementCount) {
this._elements.length += this._allocStep;
}
this._elements.copyWithin(1, 0, this._elementCount);
this._elements[0] = el;
this._elementCount++;
return new VectorCursor<T>(this, 0);
}
public append(el: T) {
if (this._elements.length === this._elementCount) {
this._elements.length += this._allocStep;
}
this._elements[this._elementCount] = el;
this._elementCount++;
return new VectorCursor<T>(this, this._elementCount - 1);
}
public *[Symbol.iterator]() {
const elements = this._elements;
const size = this._elementCount;
for (let i = 0; i < size; i++) {
yield elements[i];
}
}
public add(el: T): [boolean, VectorCursor<T>] {
return [true, this.append(el)];
}
public at(position: number): VectorCursor<T> {
if (position < 0 || position >= this._elementCount) {
throw new RangeError(`Could not get element at position ${position}: index out of range.`);
}
return new VectorCursor(this, position);
}
public delete(el: T): boolean {
for (let i = 0; i < this._elementCount; i++) {
if (el === this._elements[i]) {
this._elements.copyWithin(i, i + 1, this._elementCount);
this._elementCount--;
return true;
}
}
return false;
}
public deleteAtIndex(index: number) {
this._elements.copyWithin(index, index + 1, this._elementCount);
this._elementCount--;
}
public swap(a: number, b: number) {
const keep = this.getAt(a);
this.replace(a, this.getAt(b));
this.replace(b, keep);
}
public deleteAt(pos: VectorCursor<T>) {
this.deleteAtIndex(pos._index);
}
public deleteAll(element: T): number {
let k = 0;
let count = 0;
for (let i = 0; i < this._elementCount; i++) {
if (element !== this._elements[i]) {
this._elements[k++] = this._elements[i];
} else {
count++;
}
}
this._elementCount = k;
return count;
}
public clear() {
this._elements = [];
this._elementCount = 0;
}
public clone() {
return new Vector<T>({
elements: this,
capacity: this._elements.length,
allocStep: this._allocStep,
});
}
}
export default Vector;