Skip to content

Commit 3e8deaf

Browse files
authored
feat: added Polynomial in Maths (#397)
1 parent dda4aaf commit 3e8deaf

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Maths/Polynomial.js

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
2+
/**
3+
* Polynomials are algebraic expressions consisting of two or more algebraic terms.
4+
* Terms of a polynomial are:
5+
* 1. Coefficients e.g. 5, 4 in 5x^0, 4x^3 respectively
6+
* 2. Variables e.g. y in 3y^2
7+
* 3. Exponents e.g. 5 in y^5
8+
*
9+
* Class Polynomial constructs the polynomial using Array as an argument.
10+
* The members of array are coefficients and their indexes as exponents.
11+
*/
12+
class Polynomial {
13+
constructor (array) {
14+
this.coefficientArray = array // array of coefficients
15+
this.polynomial = '' // in terms of x e.g. (2x) + (1)
16+
this.construct()
17+
}
18+
19+
/**
20+
* Function to construct the polynomial in terms of x using the coefficientArray
21+
*/
22+
construct () {
23+
this.polynomial = this.coefficientArray.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) => {
36+
if (x !== '0') {
37+
return x
38+
}
39+
})
40+
.reverse()
41+
.join(' + ')
42+
}
43+
44+
/**
45+
* Function to display polynomial in terms of x
46+
* @returns {String} of polynomial representation in terms of x
47+
*/
48+
display () {
49+
return this.polynomial
50+
}
51+
52+
/**
53+
* Function to calculate the value of the polynomial by substituting variable x
54+
* @param {Number} value
55+
*/
56+
evaluate (value) {
57+
return this.coefficientArray.reduce((result, coefficient, exponent) => {
58+
return result + coefficient * (Math.pow(value, exponent))
59+
}, 0)
60+
}
61+
}
62+
63+
/**
64+
* Function to perform tests
65+
*/
66+
const tests = () => {
67+
const polynomialOne = new Polynomial([1, 2, 3, 4])
68+
console.log('Test 1: [1,2,3,4]')
69+
console.log('Display Polynomial ', polynomialOne.display())
70+
// (4x^3) + (3x^2) + (2x) + (1)
71+
console.log('Evaluate Polynomial value=2 ', polynomialOne.evaluate(2))
72+
// 49
73+
74+
const polynomialTwo = new Polynomial([5, 0, 0, -4, 3])
75+
console.log('Test 2: [5,0,0,-4,3]')
76+
console.log('Display Polynomial ', polynomialTwo.display())
77+
// (3x^4) + (-4x^3) + (5)
78+
console.log('Evaluate Polynomial value=1 ', polynomialTwo.evaluate(1))
79+
// 4
80+
}
81+
82+
tests()

0 commit comments

Comments
 (0)