forked from Dartameill/JS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
84 lines (69 loc) · 3 KB
/
Copy pathscript.js
File metadata and controls
84 lines (69 loc) · 3 KB
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
$(document).ready(function () {
var calc = $('.calculator');
var calcDisplay = calc.find('.calculator__display');
var calcKeys = calc.find('.calculator__key');
var calcButton = calc.find('.calculator__button');
var calcClear = calc.find('.calculator__clear');
var calcEqual = calc.find('.calculator__key--equal');
var calcPower = calc.find('.calculator__power');
var calcSpace = calc.find('.calculator__backspace');
function checkOperatorRepeat(expression) {
if(!expression) {
return true;
}
const expressionWithoutSpaces = expression.split(' ').join('');
if(expressionWithoutSpaces.length < 2) {
return true;
}
const length = expressionWithoutSpaces.length;
const lastSymbol = expressionWithoutSpaces[length - 1];
const prelastSymbol = expressionWithoutSpaces[length - 2];
// решение не идеальное, потому что например, такое выражение `8 - -9` не пройдёт прверку
// но суть ты понял, я думаю, и дальше можешь сам
return lastSymbol !== prelastSymbol || !(/[\/*\-+.]/.test(lastSymbol));
}
// https://learn.javascript.ru/keyboard-events
calcDisplay.on('keydown', (event) => {
// здесь я обычно проверяю регулярки https://regex101.com/
// https://learn.javascript.ru/regexp-character-sets-and-ranges
// первый символ - только цифра от 1 до 9 или минус (для отрицательного числа)
const arithmeticPattern = /^[1-9\-][0-9\/*\-+. ]*$/;
const key = event.key;
if (key === 'Enter') {
calcEqual.click();
return true;
}
const value = `${calcDisplay.val()}${key}`;
return key === 'ArrowLeft' || key === 'ArrowRight' || key === 'Delete' || key === 'Backspace'
// должен работать и паттерн и проверка на повторку
|| arithmeticPattern.test(value) && checkOperatorRepeat(value);
});
// INIT CALC KEYS
calcKeys.each(function () {
var current = $(this).attr('value');
$(this).text(current);
});
// ADD NUMBERS TO INPUT
calcButton.on('click', function () {
const value = calcDisplay.val() + $(this).attr('value');
if (checkOperatorRepeat(value)) {
calcDisplay.val( value );
}
});
// CLEAR INPUT
calcClear.on('click', function () {
calcDisplay.val('');
});
// SHOW RESULT
calcEqual.on('click', function () {
calcDisplay.val( eval( calcDisplay.val() ));
});
// POWER BUTTON
calcPower.on('click', function () {
calcDisplay.val( Math.pow( calcDisplay.val(), 3 ) );
});
// BACKSPACE BUTTON
calcSpace.on('click', function () {
calcDisplay.val( calcDisplay.val().substring(0, calcDisplay.val().length-1) );
});
});