Aug 22, 2020

Back to Typescript

After finishing my tutorial on C-graphics, I have shortly returned to the world of Typescript to make a small layout library. I quite like both C and Rust, and if I could chose I would prefer professionally to work with them. This being said, it doesn't take long to notice that the flexibility of Javascript really boost productivity in terms of making it very simple to write things that definitely would be more cumbersome to write in more "low level, high level" languages.

Code of the Day

  middle(): Point {
    const allPoints = this.lineSegments.reduce((acc: Point[], val: LineSegment) => {
      acc.push(val.p1);
      return acc;
    },                                         []);

    const minPoint = allPoints.reduce((acc: Point, val: Point) => {
      return Point.fromValues(
        Math.min(acc.x, val.x),
        Math.min(acc.y, val.y),
      );
    },                                allPoints[0]);

    const maxPoint = allPoints.reduce((acc: Point, val: Point) => {
      if (acc == null) {
        return val;
      }
      return Point.fromValues(
        Math.max(acc.x, val.x),
        Math.max(acc.y, val.y),
      );
    },                                allPoints[0]);

    return minPoint.plus(maxPoint.minus(minPoint).scale(0.5));
  }

Here is some code that is almost painful when you think with Rust/C glasses of all the unnecessary allocations, but that none the less gets its job done.