Created
September 22, 2022 13:58
-
-
Save deepakkumarnd/c4cd22ba3206ae4dce95f2f53960faf2 to your computer and use it in GitHub Desktop.
ImmutableList in typescript
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
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