-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
44 lines (40 loc) · 1.3 KB
/
main.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
import {
GlobalEnv,
MathCompilator,
MathEvaluator,
MathAnalyzer,
MathTokens,
RegexTokenizer,
createDisplayMessage,
getElementsByType,
ExprSymbols,
ExprCommands,
} from './src/index.js'
window.onload = () => {
const calc = document.forms['calc']
const expression = calc.elements['expression']
const buttons = getElementsByType(calc.elements, 'button')
const displayMessage = createDisplayMessage(expression.labels[0], calc, 'idle', 1500)
const calculateExpression = event => {
event.preventDefault()
try {
const parser = new MathAnalyzer(new RegexTokenizer(MathTokens))
const compilator = new MathCompilator(GlobalEnv, new MathEvaluator())
const evaliation = compilator.compile(expression.value, parser)
expression.value = evaliation()
displayMessage('Ok!', 'success')
} catch (err) {
displayMessage(err.message, 'error')
}
}
const handleExpression = event => {
event.preventDefault()
const { name } = event.target || { name: '' }
const symbol = ExprSymbols[name]
const command = ExprCommands[name]
if (command) command(expression)
else if (symbol) expression.value += symbol
}
calc.addEventListener('submit', calculateExpression)
buttons.forEach(button => button.addEventListener('click', handleExpression))
}