Skip to content

Instantly share code, notes, and snippets.

@darkcris1
Last active January 3, 2021 11:49
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 darkcris1/68afe280312a87606d2de3bb4907c513 to your computer and use it in GitHub Desktop.
Save darkcris1/68afe280312a87606d2de3bb4907c513 to your computer and use it in GitHub Desktop.
Linear Equation Solver | Sololearn
function linearSolver(equation) {
const equa = equation.split('=').map((x) => x.replace(/\s/g, ''))
const hasX = equa.find((x) => /x/.test(x))
const noX = equa.find((x) => !/x/.test(x))
let x = 0
const errorMsg = 'Invalid Equation: ' + equation
try {
if (/\b\W/.test(hasX)) {
const c = hasX.match(/(-|\+|)+(\d+x|x\d+)/)[0]
const b = Number(noX)
const a = Number(hasX.replace(c, ''))
let operator = '-'
// change the a coefficient operator to - or +
;/^(\+|)/.test(a) ? (operator = ' - ') : (operator = ' + ')
x =
Function('return ' + b + operator + a)() /
Number(c.replace(/(-|\+|)x/, ''))
} else {
x = Function('return ' + noX)() / Number(hasX.replace(/x/, ''))
}
} catch (e) {
throw new Error(errorMsg)
}
return isNaN(x) ? errorMsg : equation + '\n\n' + ' x = ' + x
}
console.log(linearSolver('2x = 1 - 3')) // -1
console.log(linearSolver('47 = -5x - 10')) // -11.4
console.log(linearSolver('x9 = 5 - 10')) // -0.5555555555555556
console.log(linearSolver('12 + 10 = -x47')) // -0.46808510638297873
console.log(linearSolver('-5x + -100 = 67')) // Invalid Equation: -5x + -100 = 67
console.log(linearSolver('10x + 140 = 57')) // x = -8.3
console.log(linearSolver('1x - 10 = 5x7')) // Invalid Equation: 1x - 10 = 5x7
console.log(linearSolver('100 - -xxx90 = 17')) // Invalid Equation: 100 - -xxx90 = 17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment