Skip to content

Commit 4862c5a

Browse files
Added result preview in editor
1 parent f68c879 commit 4862c5a

2 files changed

Lines changed: 24 additions & 12 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ Note: _The order of this list might not match the order these features will be a
6666

6767
_Release date: ???????????????????????_
6868

69-
_Work Time: 5h 40min_
69+
_Work Time: 6h 40min_
7070

7171
-
7272

pages/common.js

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ var icons = document.querySelectorAll('#result icon > *');
194194
var button = document.querySelector('#calc button');
195195
var errors = {
196196
char: 'Only numbers or +-*/(). characters are allowed.',
197-
par: 'Some parentheses are missing.'
197+
par: 'Some parentheses are missing.',
198+
syntax: 'Syntax error detected.'
198199
}
199200

200201

@@ -235,14 +236,32 @@ editor.addEventListener('keyup', function (event) {
235236
textfield.addEventListener('input', checkErrors);
236237

237238
function checkErrors(event) {
238-
var inp = event.target.value.toString().split('');
239+
// convert the input to string, split in an array, remove spaces
240+
var inp = event.target.value.toString().split('').filter(x => x != " ");
239241
// check if every character is allowed => 0123456789.+-*/()
240242
var charTest = inp.every(char => char.match(/[0-9|\+|\-|\*|\/|(|)|\.]/));
241243
// check if parentheses match
242244
var parTest = inp.filter(char => char == '(').length == inp.filter(char => char == ')').length;
243-
245+
246+
// preview result
247+
var validExpression = true;
248+
try {
249+
eval(inp.join(''));
250+
} catch (e) {
251+
if (e instanceof SyntaxError) validExpression = false;
252+
} finally {
253+
if (validExpression && charTest && parTest) result.innerText = eval(inp.join(''));
254+
}
255+
256+
// update warning tooltip
257+
var tooltip = [];
258+
if (!charTest) tooltip.push(errors.char);
259+
if (!parTest) tooltip.push(errors.par);
260+
if (!validExpression) tooltip.push(errors.syntax);
261+
icons[1].querySelector('span').innerText = tooltip.join('\n');
262+
244263
// update icon and button
245-
if (charTest && parTest) {
264+
if (charTest && parTest && validExpression) {
246265
button.disabled = false;
247266
showIcon(0);
248267
} else {
@@ -254,12 +273,5 @@ function checkErrors(event) {
254273
icons.forEach(e => e.classList.add('invisible'));
255274
icons[index].classList.remove('invisible');
256275
}
257-
258-
// update warning tooltip
259-
var tooltip = [];
260-
if (!charTest) tooltip.push(errors.char);
261-
if (!parTest) tooltip.push(errors.par);
262-
console.log(tooltip)
263-
icons[1].querySelector('span').innerText = tooltip.join('\n');
264276
}
265277

0 commit comments

Comments
 (0)