JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

HTML

<div id="question"></div>
<div id="answer"></div>
<button id="submit">Submit</button>

JavaScript

function randomName() {
	const names = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank"];
  return names[Math.floor(Math.random() * names.length)];
}

class NumberInput {
	constructor(min, max) {
  	this.min = min;
    this.max = max;
    
    this.dom = document.createElement("input");
    this.dom.type = "number";
    this.dom.min = this.min;
    this.dom.max = this.max;
  }

  value() {
  	return Number(this.dom.value);
  }
}

class AddingApples {
	constructor() {
  	const a = Math.floor(Math.random() * 10) + 1;
    const b = Math.floor(Math.random() * 10) + 1;
    
    const nameA = randomName();
    const nameB = randomName();
    
    this.vars = { a, b, nameA, nameB };
  }

  question() {
  	const { a, b, nameA, nameB } = this.vars;

  	return `${nameA} has ${a} apples and ${nameB} has ${b} apples. How many do they have in total?`;
  }

  answerInput() {
    return new NumberInput(0, 100);
  }

  checkAnswer(answer) {
  	const { a, b } = this.vars;
    return answer === a + b;
  }
}

const question = new AddingApples();
const input = question.answerInput();
document.querySelector("#question").innerText = question.question();
document.querySelector("#answer").appendChild(input.dom);
document.querySelector("#submit").addEventListener("click", function (event) {
	alert(question.checkAnswer(input.value()));
});