My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

How can I convert a randomly generated string into a functioning math equation?

Paul Jacobson's photo
Paul Jacobson
·Dec 18, 2017

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:

  1. how to parse the randomly generated equations (basically, num1 randomOperator num2 ) and interpret them as an integer, operator, and integer (respectively);
  2. calculate the solution to the equation; and
  3. 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();