This repository was archived by the owner on Apr 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
88 lines (75 loc) · 2.8 KB
/
index.ts
File metadata and controls
88 lines (75 loc) · 2.8 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
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
/**
* A basic array with a fixed size.
*
* JS arrays are dynamic by default, so a custom implementation is required to fulfill
* the course requirements.
*
* This implementation uses a JS array under the hood, which is explicitly allowed.
*
*/
export class FixedArray<T> {
private _array: T[];
private _size: number;
constructor(size: number, defaultValue?: T) {
if (size < 1)
throw RangeError(`Array size must be at least 1: ${size}`);
this._array = Array(size).fill(defaultValue);
this._size = size;
}
private isInBounds = (i: number) => !(i < 0) && i < this._size;
public size = () => this._size;
/** Get an element in the array by its index */
public get(i: number) {
if (!this.isInBounds(i))
throw ReferenceError(`Index out of bounds for array size ${this._size}: ${i}`);
return this._array[i];
}
/** Set a value in the array by index */
public set(i: number, v: T) {
if (!this.isInBounds(i))
throw ReferenceError(`Index out of bounds for array size ${this._size}: ${i}`);
this._array[i] = v;
}
/**
* Implement the iteration protocol.
* This allows an instance of this class to be iterated over using `for of`
* or the javascript spread operator `...`
*/
public *[Symbol.iterator]() {
for (let i = 0; i < this._size; i++) {
yield this._array[i];
}
}
/**
* Creates a new fixed size array of the given size and copies all this array's elements
* to it. Since there must be space for at least all the current elements, the new array
* must be larger or equal in size to the one being copied.
*
* @param size The size of the new array. Must be greater than or equal to the current size.
*/
public copy(size: number) {
if (size < this._size)
throw RangeError(`Cannot copy array to a smaller size (${size} < ${this._size})`);
const newArray = new FixedArray<T>(size);
for (let i = 0; i < this._size; i++)
newArray.set(i, this._array[i]);
return newArray;
}
/** Apply a transformation function to the given element */
public changeWithFn(i: number, transformer: (oldValue: T) => T) {
this.set(i, transformer(this.get(i)));
}
/** Call the given function with all of this array's elements in order */
public forEach(fn: (value: T, index: number, array: this) => void) {
for (let i = 0; i < this._size; i++) {
fn(this.get(i), i, this);
}
}
public map<M>(fn: (value: T, index: number, array: this) => M) {
const out = new FixedArray<M>(this._size);
for (let i = 0; i < this._size; i++) {
out.set(i, fn(this.get(i), i, this));
}
return out;
}
}