TL;DR: That time I wrote conway’s game of life in typescript

Demo : https://anthony-griff.gitlab.io/game-of-life-take-one/

Source Code : https://gitlab.com/anthony-griff/game-of-life-take-one

Keeping sharp

It’s always good to practice, and sometimes in your day to day job you don’t get the chance to break out of your current problem domain. For me I wanted a reminder of how to setup a project again from scratch. I also wanted to take a look at javascript’s iterators and generators.

Iterators & Generators : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

Yield : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

Generators

This has to be my favorite bit (the code below), using a generator to loop around a cells neighbours.

Looking at countOfNeighbours and I think I can improve on that code, with a bit of functional programming goodness. countOfNeighbours is just a sum. Just maybe I could use reduce to get the value instead?

And now that I’ve spotted it “let count: number = 0;” is an indicator of a code smell.

Are these code smells?

    let variable = 0;
    let variable = false;
    let variable = true;
    let variable = "";
 /**
   * Using a generator here, it enables a loop to iterate over
   * a cells neighbours, encapsulating that in a generator
   * @param cell The current cell
   */
  *cellNeighbours(cell: Cell): IterableIterator<Cell> {
    let neighbours: Array<Cell> = [
      { x: -1, y: -1 },
      { x: 0, y: -1 },
      { x: 1, y: -1 },
      { x: -1, y: 0 },
      { x: 1, y: 0 },
      { x: -1, y: 1 },
      { x: 0, y: 1 },
      { x: 1, y: 1 },
    ];

    for (let neighbourCell of neighbours) {
      let cx = cell.x + neighbourCell.x;
      let cy = cell.y + neighbourCell.y;
      yield { x: cx, y: cy };
    }
  }

  countOfNeighbours(cell: Cell): number {
    let count: number = 0;
    for (let neighbourCell of this.cellNeighbours(cell)) {
      if (this.isAlive(neighbourCell)) count = count + 1;
    }
    return count;
  }

// count-of-neighbours using reduce?

_.reduce(this.cellNeighbours(cell), (sum, n) => this.isAlive(n)) ? sum + 1 : sum; 
         , 0);