script.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var selection = [];
  2. $(document).ready(function () {
  3. $(".calc-button").on("click", function () {
  4. var curr = $(this).text();
  5. if (curr !== "AC" && curr !== "=" && curr !== "DEL") {
  6. selection.push(curr);
  7. updateScreen();
  8. } else if (curr === "AC") {
  9. selection = [];
  10. $("#screen").text("0");
  11. } else if (curr === "DEL") {
  12. selection.pop();
  13. if (selection.length === 0) {
  14. $("#screen").text("0");
  15. } else {
  16. updateScreen();
  17. }
  18. } else if (curr === "=") {
  19. showAnswer();
  20. }
  21. });
  22. });
  23. function updateScreen() {
  24. $("#screen").text(selection.join(""));
  25. }
  26. function showAnswer() {
  27. selection = selection.map(function (curr, index) {
  28. if (curr === "÷") {
  29. return "/";
  30. } else if (curr === "×") {
  31. return "*";
  32. } else {
  33. return curr;
  34. }
  35. });
  36. var answer;
  37. try {
  38. answer = eval(selection.join(""));
  39. } catch (e) {
  40. if (e instanceof SyntaxError) {
  41. answer = "Math error";
  42. }
  43. }
  44. selection = [];
  45. answer = (answer + "").replace("Infinity", "∞");
  46. answer = (answer + "").replace("NaN", "Error 404, logic not found");
  47. $("#screen").text(answer);
  48. }