Formula to JSON
Formula to Hungarian notation
by Génesis García Morilla
March 10, 2024
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/12.3.0/math.js"></script>
<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;
}
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)
}