Files
JavaScript/Maths/Polynomial.js
Ephraim Atta-Duncan e112434dee Add tests to Math (#423)
* Add prettier config

* test: add test to check for absolute function

* chore: es5 to es6

* test: add test to check mean function

* test: add test for sum of digit

* test: add test for factorial

* test: add test for fibonnaci

* test: add test for find HCF

* test: add test for lcm

* test: add gridget test

* test: add test for mean square error

* test: add test for modular binary exponentiation

* test: add tests for palindrome

* test: add test for pascals triangle

* test: add tests for polynomial

* test: add tests for prime check

* test: add tests for reverse polish notation

* test: add tests for sieve of eratosthenes

* test: add tests for pi estimation monte carlo method

* chore: move tests to test folder

* chore: fix standardjs errors
2020-10-12 01:17:49 +05:30

64 lines
1.6 KiB
JavaScript

/**
* Polynomials are algebraic expressions consisting of two or more algebraic terms.
* Terms of a polynomial are:
* 1. Coefficients e.g. 5, 4 in 5x^0, 4x^3 respectively
* 2. Variables e.g. y in 3y^2
* 3. Exponents e.g. 5 in y^5
*
* Class Polynomial constructs the polynomial using Array as an argument.
* The members of array are coefficients and their indexes as exponents.
*/
class Polynomial {
constructor (array) {
this.coefficientArray = array // array of coefficients
this.polynomial = '' // in terms of x e.g. (2x) + (1)
this.construct()
}
/**
* Function to construct the polynomial in terms of x using the coefficientArray
*/
construct () {
this.polynomial = this.coefficientArray
.map((coefficient, exponent) => {
if (coefficient === 0) {
return '0'
}
if (exponent === 0) {
return `(${coefficient})`
} else if (exponent === 1) {
return `(${coefficient}x)`
} else {
return `(${coefficient}x^${exponent})`
}
})
.filter((x) => {
if (x !== '0') {
return x
}
})
.reverse()
.join(' + ')
}
/**
* Function to display polynomial in terms of x
* @returns {String} of polynomial representation in terms of x
*/
display () {
return this.polynomial
}
/**
* Function to calculate the value of the polynomial by substituting variable x
* @param {Number} value
*/
evaluate (value) {
return this.coefficientArray.reduce((result, coefficient, exponent) => {
return result + coefficient * Math.pow(value, exponent)
}, 0)
}
}
export { Polynomial }