Skip to content

Instantly share code, notes, and snippets.

@gosoccerboy5
Last active March 25, 2022 20:08
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 gosoccerboy5/6b4bffbf0ee1018352f9dd54a01d198d to your computer and use it in GitHub Desktop.
Save gosoccerboy5/6b4bffbf0ee1018352f9dd54a01d198d to your computer and use it in GitHub Desktop.
A small API that can give information about a quadratic equation, including vertex, zeros, y-intercept, and coefficients.
// Parse a quadratic, find its coefficients, and feed it into the "quadratic" function
function parseQuadratic(input) {
const refined = input.toLowerCase().replaceAll(" ", "");
// A regex that matches and finds the coefficients in a quadratic in the format ax^2+bx+c
const matches = refined.match(/(-?[0-9.]*)[a-z]\^2(?:([+-][0-9.]*)[a-z])?([+-][0-9.]*)?/)
.slice(1) // We don't want the first value (which is the full match)
.map(str => Number( // we will convert our refined coefficients from a string to a number
(str ?? "0") // If the current item in the matches list is undefined, it was not provided, the coefficient will be 0
.replace(/^[+-]?$/, x => x + "1"))); // If we have only +/- or even no coefficient along with the x, we assume it is 1
return quadratic(...matches); // Apply our coefficients to the "quadratic" function
}
// Generate statistics about a quadratic equation, including zeros, vertex, coefficients, and more
function quadratic(a, b, c) {
return {
zeros: [(-b + Math.sqrt(b**2 - 4*a*c)) / (2*a), (-b - Math.sqrt(b**2 - 4*a*c)) / (2*a)],
vertex: [-b / (2*a), a * (-b / (2*a))**2 + b * (-b / (2*a)) + c],
yIntercept: c,
mirrorX: -b / (2*a),
coefficients: [a, b, c],
discriminant: b**2-4*a*c,
valueAt(x) {
// Applies the quadratic to any x value
return a * (x**2) + b*x + c;
}
}
}
console.log(parseQuadratic(prompt("Enter a quadratic in the form of ax^2+bx+c"))); // Prompt the user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment