#How would you refactor this?
14 messages · Page 1 of 1 (latest)
Yeah, lookup table is usually my preference:
type Dir = keyof typeof turnCW;
const turnCW = { up: "right", right: "down", down: "left", left: "up" } as const;
const turnCCW = { up: "left", right: "up", down: "right", left: "down" } as const;
function turn(turnDirection: "right" | "left", dir: Dir) {
const rotation = turnDirection === "right" ? turnCW : turnCCW;
return rotation[dir];
}
Probably not a private attribute - could do static attached to the class or top of the module.
Or yeah, within the function is fine too.
The same but noisier, I guess.
You can still make an object with enum keys:
const turnCW = {
[CardinalDirection.North]: CardinalDirection.East,
[CardinalDirection.East]: CardinalDirection.South,
[CardinalDirection.South]: CardinalDirection.West,
[CardinalDirection.West]: CardinalDirection.North
};
const turnCCW = {
[CardinalDirection.North]: CardinalDirection.West,
[CardinalDirection.East]: CardinalDirection.North,
[CardinalDirection.South]: CardinalDirection.East,
[CardinalDirection.West]: CardinalDirection.South
};
Probably bring the two lookup tables to top level/static so it's not creating them on every call.
That does not affect anything, you can still bring things to top level.
Probably should actually type your direction propery to be specifically CardinalDirection, not number.
Not really; looks fine to me.
no need for a lookup table
turn(turnDirection: TurnDirection): void {
if (turnDirection === TurnDirection.Right) {
this.direction = (this.direction + 1) % 4;
} else {
this.direction = (this.direction + 3) % 4;
}
}
walk could be simplified even more if direction is [number, number]:
this.location[0] += this.direction[0] * blocks;
this.location[1] += this.direction[1] * blocks;