-
Notifications
You must be signed in to change notification settings - Fork 0
/
diffeq.js
99 lines (85 loc) · 1.94 KB
/
diffeq.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const splitEq = eq => eq.split('+')
const splitExp = exp => exp.split('^')
const splitCoe = str => {
const index = str.indexOf('x')
return index === -1
? [str, '']
: [str.substring(0, index), str.substring(index)]
}
const handleMinus = str =>
str
.replace(/-x/g, '-1x')
.replace(/-/g, '+-')
.replace(/^\+/, '')
const parseEq = str =>
splitEq(handleMinus(str))
.map(splitExp)
.map(x => [].concat(splitCoe(x[0]), x.slice(1)))
const calcDerivative = arr =>
arr[1] === 'x'
? [].concat(
(parseInt(arr[0]) || 1) * (arr[2] || 1),
arr[1],
(arr[2] || 1) - 1
)
: [0]
const reduceTerms = arr =>
arr[1] === 'x' && arr[2] === 0
? [].concat(arr[0])
: arr
const differentiateToArrays = eqArr =>
eqArr
.map(calcDerivative)
.map(reduceTerms)
const calcPolyElem = (acc, val) => {
let num = val.length === 1
? val[0]
: val[0] * Math.pow(val[1], val[2])
return acc + num
}
const solve = subEqArr =>
subEqArr.reduce(calcPolyElem, 0)
const substituteX = (eqArr, point) =>
eqArr.map(x => {
let result = [].concat(x)
if (result[1] === 'x') {
result[1] = point
}
return result
})
const differentiateAndEval = (eq, point) =>
solve(substituteX(differentiateToArrays(parseEq(eq)), point))
const renderEquation = eqArr =>
eqArr
.filter(x => x[0] !== 0)
.map(x => {
let exp = ''
if (x.length === 1) {
exp = exp + x[0]
} else if (x[2] === 1) {
exp = exp + x[0] + x[1]
} else {
exp = exp + x[0] + x[1] + '^' + x[2]
}
return exp
})
.join('+')
.replace('+-', '-')
const differentiate = eq =>
renderEquation(differentiateToArrays(parseEq(eq)))
module.exports = {
differentiateAndEval,
splitEq,
splitExp,
splitCoe,
parseEq,
calcDerivative,
differentiateToArrays,
calcPolyElem,
reduceTerms,
solve,
substituteX,
handleMinus,
renderEquation,
differentiate
}