Created
December 22, 2021 21:42
-
-
Save eschwartz/47cd54b0b3bd44f47f66e5232de8879f to your computer and use it in GitHub Desktop.
Regex Solution to Server Side Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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