/
differentiate.ts
73 lines (58 loc) · 1.29 KB
/
differentiate.ts
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
const diffTerm = (term: string): string => {
let result: string = ""
let coeffStr: string = ""
let i = 0
for (i = 0; term[i] != "x"; i++) {
if (term[i] == " ") {
continue
}
coeffStr += term[i]
}
let coeff = parseInt(coeffStr)
let powStr = ""
for (i = i + 2; i != term.length && term[i] != " "; i++) {
powStr += term[i]
}
let power = parseInt(powStr)
coeff = coeff * power
// console.log(`coeff is ${coeff}`)
coeffStr = coeff.toString()
// console.log(`coeffStr is ${coeffStr}`)
powStr = (power - 1).toString()
result += coeffStr + "x^" + powStr
return result
}
/**
* @remarks
* This is a not a numerical method.
*
* @returns differentiation of given expression.
* @param expression - Expression to differentiate.
*
* @example
*```ts
*diff("4x^3 - 3x^1 + 2x^2")
*```
*
* */
export const differentiate = (expression: string): string => {
let result: string = ""
// const expSplit = expression.split(/[+-]+/)
const expSplit = expression.split(" ")
let i: number = 0
while (i < expSplit.length) {
if (expSplit[i] == "+") {
result += " + "
i++
continue
}
if (expSplit[i] == "-") {
result += " - "
i++
continue
}
result += diffTerm(expSplit[i])
i++
}
return result
}