gengns ES

An entry from the gengns log, written by Génesis García Morilla · · HTML5, JavaScript

Formula to JSON

Define formula using variables and transform it to JSON if it’s a valid math expression using Math.js

JavaScript

const input = document.querySelector('input')
const p = document.querySelector('p')

// Sample variable values
const variables = {
  A: 8,
  B: 5,
  C: -3,
  D: 10
}

// Validate formula written in the input
input.oninput = () => {
  try {
    const result = math.evaluate(input.value, variables)
    input.setCustomValidity('')
    p.innerText = input.value ? 'Good!' : 'No formula'
  } catch (error) {
    input.setCustomValidity(error.message)
    p.innerText = 'Wrong!'
  }
}

// On Submit
document.querySelector('form').onsubmit = e => {
  e.preventDefault()
  // Parse the equation to JSON
  const node = math.parse(input.value)
  // Hungarian notation  
  p.innerText = JSON.stringify(hungarian_notation(node))
}

// Recursive tansform to Hungarian Notation
function hungarian_notation(node) {
  if (node.isOperatorNode)
    return { [node.op]: node.args.map(hungarian_notation) }
  else if (node.isSymbolNode)
    return node.name
  else if (node.isConstantNode)
    return node.value
  else if (node.isParenthesisNode)
    return hungarian_notation(node.content)
}

HTML

<h3>Formula to JSON</h3>

<form>
   <input placeholder="(A + B) >= 10 and D < C * 2">
   <button>Transform</button>
</form>

<p>No formula</p>

CSS

body {
  font-family: system-ui, sans-serif;
  display: grid;
  place-items: center;
}

form {
  display: grid;
  grid-gap: 10px;
}

input {
  font-size: 16px;
}
Open in JSFiddle

Tags: formula, input, JSON, Math.js, validator