Skip to content

Instantly share code, notes, and snippets.

@dawiidio
Created December 17, 2021 11:05
Show Gist options
  • Select an option

  • Save dawiidio/2e76d6ea237380d9ef34fcd1ff6732c6 to your computer and use it in GitHub Desktop.

Select an option

Save dawiidio/2e76d6ea237380d9ef34fcd1ff6732c6 to your computer and use it in GitHub Desktop.

Revisions

  1. dawiidio created this gist Dec 17, 2021.
    30 changes: 30 additions & 0 deletions nestedCounter.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    class Counter {
    private child: Counter[] = [];
    private value: number = 0;
    private destroyed: boolean = false;

    increase(): number {
    if (this.destroyed)
    throw new Error(`destroyed counter can not be increased`);

    return ++this.value;
    }

    getCount(): number {
    return this.value;
    }

    destroy() {
    this.destroyed = true;

    this.child.forEach(c => c.destroy());
    }

    spawn(): Counter {
    const child = new Counter();

    this.child.push(child);

    return child;
    }
    }