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.

Revisions

  1. deepakkumarnd created this gist Sep 22, 2022.
    41 changes: 41 additions & 0 deletions ImmutableList.ts
    Original 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)