Skip to content

Instantly share code, notes, and snippets.

@FelixLuciano
Last active July 17, 2020 17:01
Show Gist options
  • Save FelixLuciano/38b6d927f3bfa085394b0eba86f1e0ab to your computer and use it in GitHub Desktop.
Save FelixLuciano/38b6d927f3bfa085394b0eba86f1e0ab to your computer and use it in GitHub Desktop.
Reads a second degree equation in a string and calculates its root using the Bhaskara formula
function calculateBhaskara (a, b, c) {
if (a === 0) throw(`the coefficient 'a' cannot be 0 in a second degree equation`)
const delta = calculateDelta (a, b, c)
const solution = []
if (delta < 0) return solution
const sqrtDelta = Math.sqrt(delta)
solution.push((-b - sqrtDelta) / (2 * a))
if (delta > 0) solution.push((-b + sqrtDelta) / (2 * a))
return solution
}
calculateBhaskara(1, -4, 3) // [ 1, 3 ]
calculateBhaskara(1, -2, 1) // [ 1 ]
calculateBhaskara(1, -2, 2) // [ ]
calculateBhaskara(0, 1, 1) // 'Uncaught the coefficient 'a' cannot be 0 in a second degree equation'
function calculateDelta (a, b, c) {
return b**2 - 4 * a * c
}
const splitEntryes = /(?<!\+|\-|^)\+(?!$)|(?<!\+|\-|^)(?=\-(?!$))/g
const matchX = /x/i
const matchXSquared = /x{2}|x\*\*2|x\^2|x²/i
const matchNeutralOperator = /(\+|\-|^)(?=\D)(?!\+|\-|$|\.)/g
const replaceNeutralOperator = '$11'
const matchNumbers = /(?<!\*\*|\^)(\/?\-?[\d.]+)/g
const fixOperations = entry =>
entry.startsWith('/') ? 1 / Number(entry.slice(1)) : Number(entry)
const reduceValue = (accumulator, currentValue) =>
accumulator * currentValue
function extractCoeficients (sentence) {
const entryes = sentence.split(splitEntryes)
const coeficients = { a: 0, b: 0, c: 0 }
for (let entry of entryes) {
const value = entry
.replace(matchNeutralOperator, replaceNeutralOperator)
.match(matchNumbers)
.map(fixOperations)
.reduce(reduceValue)
let key = null
if (entry.match(matchXSquared)) key = 'a'
else if (entry.match(matchX)) key = 'b'
else key = 'c'
coeficients[key] += value
}
return coeficients
}
extractCoeficients('x²-x+1') // { a: 1, b: -1, c: 1 }
extractCoeficients('x^2+1.5x+3/2') // { a: 1, b: 1.5, c: 1.5 }
extractCoeficients('x²+xx+x**2+x^2') // { a: 4, b: 0, c: 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment