Created
May 17, 2019 14:43
-
-
Save grossvogel/aa396b74b8db3cba70b58b75fd666c97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Polynomial { | |
/** | |
* @param {array} coefficients | |
* with coefficients[i] being the coefficient for X^i | |
*/ | |
constructor(coefficients) { | |
// remove leading 0s, so 0x^2 + 2x + 1 becomes 2x + 1 | |
this._coefficients = this._trimCoefficients(coefficients); | |
} | |
get coefficients() { | |
return this._coefficients; | |
} | |
evaluate(x) { | |
const reducer = (y, coefficient, power) => | |
y + coefficient * Math.pow(x, power); | |
return this.coefficients.reduce(reducer, 0); | |
} | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment