Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@
* [PowLogarithmic](Maths/PowLogarithmic.js)
* [PrimeCheck](Maths/PrimeCheck.js)
* [PrimeFactors](Maths/PrimeFactors.js)
* [QuadraticFormula](Maths/QuadraticFormula.js)
* [RadianToDegree](Maths/RadianToDegree.js)
* [ReverseNumber](Maths/ReverseNumber.js)
* [ReversePolishNotation](Maths/ReversePolishNotation.js)
Expand Down
29 changes: 29 additions & 0 deletions Maths/QuadraticFormula.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @function quadraticFormula
* @description This script will find the the roots of a quadratic equation.
* @param {number} a
* @param {number} b
* @param {number} c
* @return {array}
* @see https://en.wikipedia.org/wiki/Quadratic_formula
* @example quadraticFormula(1, -3, -4) = [4, -1]
* @example quadraticFormula(1, 5, 6) = [-2, -3]
* @example quadraticFormula(1, -3, 8) = []
*/

const solveQuadraticEquation = (a, b, c) => {
if (typeof a !== 'number' || typeof b !== 'number' || typeof c !== 'number') {
return new TypeError('Some argument is not a number.')
}
const discriminant = (b ** 2) - (4 * a * c)
const denominator = 2 * a
let answer = []
if (discriminant >= 0) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please distinguish discriminant == 0 here to only add a single item to answer in that case.

const x1 = (-b + Math.sqrt(discriminant)) / denominator
const x2 = (-b - Math.sqrt(discriminant)) / denominator
answer = [x1, x2]
}
return answer
}

export { solveQuadraticEquation }
8 changes: 8 additions & 0 deletions Maths/test/QuadraticFormula.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { solveQuadraticEquation } from '../QuadraticFormula'

test('Quadratic Equation', () => {
expect(solveQuadraticEquation(1, -3, -4)).toStrictEqual([4, -1])
expect(solveQuadraticEquation(1, 5, 6)).toStrictEqual([-2, -3])
expect(solveQuadraticEquation(1, -3, 8)).toStrictEqual([])
expect(solveQuadraticEquation(1, -2, 9)).toStrictEqual([])
})
Loading