Created
September 22, 2022 13:58
-
-
Save deepakkumarnd/c4cd22ba3206ae4dce95f2f53960faf2 to your computer and use it in GitHub Desktop.
Revisions
-
deepakkumarnd created this gist
Sep 22, 2022 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,41 @@ 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)