A Number Guessing Game in JavaScript Node.js

Create a simple REPL game using npm package readline-sync.

In [ ]:
 

This is a rough translation of the REPL game done in this post.

The code below has a readline-sync dependency.

const readline_sync = require("readline-sync"),
  randint = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min,
  [MIN, MAX] = [1, 10],
  ANSWER = randint(MIN, MAX),
  QUIT = "quit",
  ExitWords = new Set([QUIT, "q", "bye", "exit", ANSWER.toString()]),
  shouldExit = item => ExitWords.has(item),
  MAX_GUESSES = 3;
let counter = 0,
  message = "";

const count = () => (counter += 1);

function getMessage(item) {
  if (shouldExit(item)) return QUIT;
  const message = `"${item}" is not a valid number`,
    guess = parseInt(item, 10) || message;
  if (guess < MIN || guess > MAX) return `"${guess}" is out of range`;
  if (guess === ANSWER) {
    return `"${guess}" is correct.`;
  } else if (guess === message) {
    return message;
  } else {
    const hint = guess < ANSWER ? "higher" : "lower";
    return `Guess ${hint}`;
  }
}

function identity(item) {
  console.log(getMessage(item));
  count();
  return item;
}

const echo = function echo() {
  return (
    [
      shouldExit(
        identity(
          readline_sync.question(`Type a number between ${MIN} and ${MAX}:\n`)
        )
      ),
      counter >= MAX_GUESSES
    ].some(i => i) || echo()
  );
};
echo();
if (counter > MAX_GUESSES) {
  message = `Max guesses exceeded: ${MAX_GUESSES}`;
} else {
  message = `The answer is correct: ${ANSWER}`;
}
[
  message,
  `The answer is ${ANSWER}.`,
  `${counter} attempts.`,
  "Exiting."
].forEach(item => console.log(item));