Write the logic for a quiz app

“Quiz engine”, a Black belt challenge from the CurlyScript Dojo. It uses what Senior Year: Capstone Projects: Build Real Apps teaches, and 3 tests check your answer.

The challenge

Write createQuiz(questions) returning an object with current() (the current question, or null when finished), answer(choiceIndex) (returns true or false and moves to the next question) and result() returning { score, total, finished }. Each question is { q, choices, answer }.

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • Current() shows the first question: (() => { const quiz = createQuiz([{ q: "1+1", choices: ["2", "3"], answer: 0 }]); return quiz.current().q; })() gives "1+1"
  • Answers are checked and scored: (() => { const quiz = createQuiz([{ q: "a", choices: ["x", "y"], answer: 1 }, { q: "b", choices: ["x", "y"], answer: 0 }]); return [quiz.answer(1), quiz.answer(1), quiz.result()]; })() gives [true, false, { score: 1, total: 2, finished: true }]
  • Current() is null at the end: (() => { const quiz = createQuiz([{ q: "a", choices: ["x"], answer: 0 }]); quiz.answer(0); return quiz.current(); })() gives null

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Keep let index = 0; and let score = 0; in the closure: that’s your state.

Hint 2

questions[index] ?? null handles the end of the quiz neatly.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function createQuiz(questions) {
  let index = 0;
  let score = 0;
  return {
    current() {
      return questions[index] ?? null;
    },
    answer(choice) {
      const correct = questions[index].answer === choice;
      if (correct) score++;
      index++;
      return correct;
    },
    result() {
      return { score, total: questions.length, finished: index >= questions.length };
    },
  };
}

Learn what you need

This exercise uses what Senior Year: Capstone Projects: Build Real Apps teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning