How can I convert a randomly generated string into a functioning math equation?
Hi, I'm working on an open source project for my kids and I could use some feedback/advice. My project's working title is called "Practice Math".
The idea is to randomly generate math equations for my kids to practice their math (and anyone else who finds the site useful). This is roughly what it looks like at the moment:
I've written JavaScript code to randomly generate the number values and to select an operator from an array.
The steps I need some help with are:
- how to parse the randomly generated equations (basically,
num1 randomOperator num2
) and interpret them as an integer, operator, and integer (respectively); - calculate the solution to the equation; and
- capture the solution into a variable that I can use to compare the answer provided by the kids when they answer each equation.
I'd appreciate any pointers here. I've gone completely blank on possible solutions.
Here is most of the code (I haven't included an event listener on the "Next" button - it isn't relevant to this question, I don't think - you can view the current code in my repo though):
const container = (document.querySelector('.container'));
const eq = document.querySelector('.equation');
let operator;
const btnNext = document.querySelector('#btn_next');
const operators = ['+', '-', '*'];
// const solutions = JSON.parse(localStorage.getItem('solutions')) || [];
// 1. Calculate random numbers
function randomNum(min, max) {
return Math.floor(Math.random() * 1000) + 1;
}
// 2. Randomly select an operator
const randomOperator = operators[Math.floor(Math.random()*operators.length)];
console.log(randomOperator);
// 4. Populate the fields with randomly generated values
function calcValues() {
const num1 = randomNum(10, 999);
const num2 = randomNum(10, 999);
eq.textContent = `
${num1} ${randomOperator} ${num2}`;
}
calcValues();