@@ -2,29 +2,48 @@ const display = document.querySelector("#display");
22const buttons = document . querySelectorAll ( "button" ) ;
33
44buttons . forEach ( ( item ) => {
5- item . onclick = ( ) => {
6- if ( item . id == "clear" ) {
7- display . innerText = "" ;
8- } else if ( item . id == "backspace" ) {
9- let string = display . innerText . toString ( ) ;
10- display . innerText = string . substr ( 0 , string . length - 1 ) ;
11- } else if ( display . innerText != "" && item . id == "equal" ) {
12- display . innerText = eval ( display . innerText ) ;
13- } else if ( display . innerText == "" && item . id == "equal" ) {
14- display . innerText = "Empty!" ;
15- setTimeout ( ( ) => ( display . innerText = "" ) , 2000 ) ;
16- } else {
17- display . innerText += item . id ;
5+ item . onclick = ( ) => {
6+ if ( item . id == "clear" ) {
7+ display . innerText = "" ;
8+ } else if ( item . id == "backspace" ) {
9+ let string = display . innerText . toString ( ) ;
10+ display . innerText = string . substr ( 0 , string . length - 1 ) ;
11+ } else if ( display . innerText != "" && item . id == "equal" ) {
12+ try {
13+ if ( display . innerText . includes ( "/0" ) ) {
14+ throw new Error ( "Division by zero" ) ;
1815 }
19- } ;
16+ display . innerText = Function (
17+ '"use strict";return (' + display . innerText + ")"
18+ ) ( ) ;
19+ } catch ( e ) {
20+ display . innerText = "Cannot divide by zero!" ;
21+ setTimeout ( ( ) => ( display . innerText = "" ) , 2000 ) ;
22+ }
23+ } else if ( display . innerText == "" && item . id == "equal" ) {
24+ display . innerText = "Empty!" ;
25+ setTimeout ( ( ) => ( display . innerText = "" ) , 2000 ) ;
26+ } else {
27+ const lastChar = display . innerText . slice ( - 1 ) ;
28+ if (
29+ [ "+" , "-" , "*" , "/" ] . includes ( lastChar ) &&
30+ [ "+" , "-" , "*" , "/" ] . includes ( item . innerText )
31+ ) {
32+ // Prevent adding multiple consecutive operators
33+ display . innerText = display . innerText . slice ( 0 , - 1 ) + item . innerText ;
34+ } else {
35+ display . innerText += item . innerText ;
36+ }
37+ }
38+ } ;
2039} ) ;
2140
2241const themeToggleBtn = document . querySelector ( ".theme-toggler" ) ;
2342const calculator = document . querySelector ( ".calculator" ) ;
2443const toggleIcon = document . querySelector ( ".toggler-icon" ) ;
2544let isDark = true ;
2645themeToggleBtn . onclick = ( ) => {
27- calculator . classList . toggle ( "dark" ) ;
28- themeToggleBtn . classList . toggle ( "active" ) ;
29- isDark = ! isDark ;
30- } ;
46+ calculator . classList . toggle ( "dark" ) ;
47+ themeToggleBtn . classList . toggle ( "active" ) ;
48+ isDark = ! isDark ;
49+ } ;
0 commit comments