Skip to content

Instantly share code, notes, and snippets.

@deepakkumarnd
Created September 22, 2022 13:58
Show Gist options
  • Save deepakkumarnd/c4cd22ba3206ae4dce95f2f53960faf2 to your computer and use it in GitHub Desktop.
Save deepakkumarnd/c4cd22ba3206ae4dce95f2f53960faf2 to your computer and use it in GitHub Desktop.
ImmutableList in typescript
abstract class ImmutableList<T> {
abstract add(elem: T): ImmutableList<T>
abstract forEach(fn: (x: T) => void): void
}
class Cons<T> implements ImmutableList<T> {
readonly el: T
readonly next: ImmutableList<T>
constructor(elem: T, list: ImmutableList<T> = Nil) {
this.el = elem
this.next = list
}
add(elem: T): ImmutableList<T> {
return new Cons(elem, this)
}
forEach(fn: (x: T) => void): void {
fn(this.el)
this.next.forEach(fn)
}
}
class EmptyList extends ImmutableList<never> {
add(elem: never): ImmutableList<never> {
return this
}
forEach(fn: (x: never) => void): void {}
}
const Nil = new EmptyList()
let list: ImmutableList<number> = new Cons(1)
list = list.add(2)
list = list.add(3)
list.forEach(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment