Skip to main content
1 of 2
Carcigenicate
  • 16.3k
  • 3
  • 35
  • 80

It could be made more functional by avoiding the mutation of acc. The effects are contained within judgeCircle so it's not a big deal, but it feels like if you're going to mutate the accumulator, you might as well just use an imperative loop.

I also preferred to be explicit about the final check. I find the intent of !h && !v isn't quite as clear as h == 0 && v == 0;.

I ended up with:

const judgeCircle3 = moves => {
  const [hori, vert] = [...moves].reduce(([h, v], move) => {
    switch(move) {
      case "U":
        return [h, v + 1];

      case "D":
        return [h, v - 1];

      case "R":
        return [h + 1, v];

      case "L":
        return [h - 1, v];
    }
    
  }, [0, 0]);

  return hori == 0 && vert == 0;
};

I also got rid of the default since it didn't seem to be doing anything. You could have done error handling in there (and should in most cases), but if it's a challenge with predefined input, that's probably not necessary unless it's part of the challenge.

Carcigenicate
  • 16.3k
  • 3
  • 35
  • 80