* 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 arg
| 9 | * The members of array are coefficients and their indexes as exponents. |
| 10 | */ |
| 11 | class Polynomial { |
| 12 | constructor(array) { |
| 13 | this.coefficientArray = array // array of coefficients |
| 14 | this.polynomial = '' // in terms of x e.g., (2x) + (1) |
| 15 | this.construct() |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Function to construct the polynomial in terms of x using the coefficientArray |
| 20 | */ |
| 21 | construct() { |
| 22 | this.polynomial = this.coefficientArray |
| 23 | .map((coefficient, exponent) => { |
| 24 | if (coefficient === 0) { |
| 25 | return '0' |
| 26 | } |
| 27 | if (exponent === 0) { |
| 28 | return `(${coefficient})` |
| 29 | } else if (exponent === 1) { |
| 30 | return `(${coefficient}x)` |
| 31 | } else { |
| 32 | return `(${coefficient}x^${exponent})` |
| 33 | } |
| 34 | }) |
| 35 | .filter((x) => x !== '0') |
| 36 | .reverse() |
| 37 | .join(' + ') |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Function to display polynomial in terms of x |
| 42 | * @returns {String} of polynomial representation in terms of x |
| 43 | */ |
| 44 | display() { |
| 45 | return this.polynomial |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Function to calculate the value of the polynomial by substituting variable x |
| 50 | * @param {Number} value |
| 51 | */ |
| 52 | evaluate(value) { |
| 53 | return this.coefficientArray.reduce((result, coefficient, exponent) => { |
| 54 | return result + coefficient * Math.pow(value, exponent) |
| 55 | }, 0) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export { Polynomial } |
nothing calls this directly
no outgoing calls
no test coverage detected