Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Created December 22, 2021 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eschwartz/47cd54b0b3bd44f47f66e5232de8879f to your computer and use it in GitHub Desktop.
Save eschwartz/47cd54b0b3bd44f47f66e5232de8879f to your computer and use it in GitHub Desktop.
Regex Solution to Server Side Calculator
// Track the equation as a string
let equation = '';
// 🤯 🤯 🤯 🤯 🤯 🤯 🤯
// This regular expression defines a set of "rules" for
// how our equation string should look
// It also tells us how to break apart the different sections of the
// string into "groups"
// These are super powerful, though not always so easy to use 😉
let equationRegEx = /^([0-9]+(\.[0-9]+)?)?([\+\-\/\*])?([0-9]+(\.[0-9]+)?)?$/
function onInput() {
// Add the clicked button to the equation string
let nextEquation = equation += $(this).text();
// Parse the equation string into "groups"
let matches = nextEquation.match(equationRegEx);
// If the equation does not match our regular expression,
// show an error
if (!matches) {
alert('Invalid equation!');
return;
}
// Grab each matching "group" from the equation
// to get our parsed equation object
let submission = {
firstNum: Number(matches[1]),
operator: matches[3],
secondNum: Number(matches[2]),
}
// etc...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment