Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created December 30, 2022 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laphilosophia/af10f3c84d79a00ac0db9a38c5a0d4d1 to your computer and use it in GitHub Desktop.
Save laphilosophia/af10f3c84d79a00ac0db9a38c5a0d4d1 to your computer and use it in GitHub Desktop.
simple immutable class library
export class ImmutableUtility<T> {
#draft: any
constructor(array: Array<T>) {
if (array.length === 0) {
throw new Error('Out of bounds...')
}
this.#draft = [...array]
}
get all(): Array<T> {
return this.#draft
}
public has(item: any) {
return this.#draft.includes(item)
}
public peek() {
return this.#draft[this.#draft.length - 1]
}
public splice(start: number, count: number, ...item: Array<T>) {
return [...this.#draft.slice(0, start), ...item, ...this.#draft.slice(start + count)]
}
public insert(item: any, pos: 'before' | 'after' | number) {
switch (pos) {
case 'before':
this.#draft = [item, ...this.#draft]
break
case 'after':
this.#draft = [...this.#draft, item]
break
default:
if (typeof pos !== 'number') {
throw new Error(`Position cannot be a ${typeof pos}.`)
}
this.#draft = this.splice(0, pos, item)
break
}
}
public remove(index: number) {
return (this.#draft = [...this.#draft.slice(0, index), ...this.#draft.slice(index + 1)])
}
public reverse() {
return (this.#draft = [...this.#draft].reverse())
}
public produce(handler: (draft: Array<T>) => void): void {
if (typeof handler !== 'function') return
this.#draft = [...this.#draft, handler(this.#draft)]
}
// measure(cb: any) {
// const begin = (globalThis || window).performance.now()
// cb()
// const end = (globalThis || window).performance.now()
// console.log(cb(), `-> it took ${(end - begin).toFixed(3)} ms`)
// }
}
export function Immutable<T>(array: Array<T>): ImmutableUtility<T> {
const immutable = new ImmutableUtility<T>(array)
return immutable
}
export default Immutable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment