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.
It prints
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(); })()givesnull
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
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.