Created
November 1, 2021 18:00
-
-
Save trevor-atlas/baf3d8a877193b3c809d09fdde2fbdc3 to your computer and use it in GitHub Desktop.
Reimplement javascript arrays. You can not use an array internally to hold data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ArrayLike<T> implements Iterable<T> { | |
private _values: Record<number, T> = {}; | |
private _size: number; | |
constructor(...values: T[]) { | |
this._values = {}; | |
this._size = 0; | |
values.forEach(val => this.add(val)); | |
} | |
add(val: T): void { | |
this._values[this._size] = val; | |
this._size++; | |
} | |
remove(): void { | |
if (this._size > 0) { | |
delete this._values[this._size - 1]; | |
this._size--; | |
} | |
} | |
get(): T { | |
if (this._size > 0) { | |
return this._values[this._size - 1]; | |
} | |
return null; | |
} | |
getAt(index: number): T { | |
if (index < 0 || index >= this._size) { | |
return null; | |
} | |
return this._values[index]; | |
} | |
setAt(index: number, val: T): void { | |
if (index < 0 || index >= this._size) { | |
return; | |
} | |
this._values[index] = val; | |
} | |
size(): number { | |
return this._size; | |
} | |
isEmpty(): boolean { | |
return this._size === 0; | |
} | |
clear(): void { | |
Object.keys(this._values).forEach(key => { | |
delete this._values[key]; | |
}); | |
this._size = 0; | |
} | |
[Symbol.iterator]() { | |
const size = this._size; | |
const values = Object.values(this._values); | |
let index = 0; | |
return { | |
next(): IteratorResult<T> { | |
if (index < size) { | |
const value = values[index]; | |
index++; | |
return { | |
value, | |
done: false | |
}; | |
} | |
return { | |
value: undefined, | |
done: true | |
}; | |
} | |
}; | |
} | |
toString(): string { | |
return `[${Object.values(this._values).map(val => val.toString()).join(', ')}]`; | |
} | |
} | |
const values = new ArrayLike<number>(1, 5, 10, 20, 50, 100, 200); | |
for (const val of values) { | |
console.log(val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment