calc_test.cljc 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. (ns frontend.extensions.calc-test
  2. (:require [clojure.test :as test :refer [deftest testing is are]]
  3. [frontend.extensions.calc :as calc]))
  4. (defn run [expr]
  5. {:pre [(string? expr)]}
  6. (first (calc/eval (calc/parse expr))))
  7. (deftest basic-arithmetic
  8. (testing "numbers are parsed as expected"
  9. (are [value expr] (= value (run expr))
  10. 1 "1"
  11. 1 " 1 "
  12. 98123 "98123"
  13. 1.0 " 1.0 "
  14. 22.1124131 "22.1124131"
  15. 100.01231 " 100.01231 "))
  16. (testing "basic operations work"
  17. (are [value expr] (= value (run expr))
  18. 1 "1 + 0"
  19. 1 "1 + 1 - 1 "
  20. 3 "1+2"
  21. 3 " 1 +2 "
  22. 1 "(2-1 ) "
  23. 211 "100 + 111"
  24. 0 "1 + 2 + 3 + 4 + 5 -1-2-3-4-5"
  25. 1 "1 * 1"
  26. 2 "1*2"
  27. 9 " 3 *3"
  28. 1 " 2 * 3 / 3 / 2"
  29. #?(:clj 1/2
  30. :cljs 0.5) " 1 / 2"
  31. 0.5 " 1/ 2.0"))
  32. (testing "power"
  33. (are [value expr] (= value (run expr))
  34. 1.0 "1 ^ 0"
  35. 4.0 "2^2 "
  36. 27.0 " 3^ 3"
  37. 16.0 "2 ^ 2 ^ 2"
  38. 256.0 "4.000 ^ 4.0"))
  39. (testing "operator precedence"
  40. (are [value expr] (= value (run expr))
  41. 1 "1 + 0 * 2"
  42. 1 "2 * 1 - 1 "
  43. 4 "8 / 4 + 2 * 1 - 25 * 0 / 1"
  44. 14.0 "3 *2 ^ 2 + 1 * 2"
  45. 74.0 "((3*2) ^ 2 + 1) * 2"
  46. 432.0 "(3*2) ^ (2 + 1) * 2"
  47. 97.0 "(2 * 3) * 2 ^ (2 * 2) + 1"
  48. 4.0 "2 * 3 / 2 ^ 2 * 2 + 1"))
  49. (testing "scientific functions"
  50. (are [value expr] (= value (run expr))
  51. 1.0 "cos( 0 * 1 )"
  52. 0.0 "sin( 1 -1 )"
  53. 0.0 "atan(tan(0))"
  54. 1.0 "sin(asin(0)) + 1"
  55. 0.0 "acos(cos(0))"
  56. 5.0 "2 * log(10) + 3"
  57. 10.0 "ln(1) + 10")))
  58. (deftest variables
  59. (testing "variables can be remembered"
  60. (are [final-env expr] (let [env (calc/new-env)]
  61. (calc/eval env (calc/parse expr))
  62. (= final-env @env))
  63. {"a" 1} "a = 1"
  64. {"variable" 1} "variable = 1 + 0 * 2"
  65. {"x" 1} "x= 2 * 1 - 1 "
  66. {"y" 4} "y =8 / 4 + 2 * 1 - 25 * 0 / 1"
  67. {"zzz" 14.0} "zzz=3 *2 ^ 2 + 1 * 2"
  68. {"foo" 74.0} "foo = (((3*2) ^ 2 + 1) * 2)"))
  69. (testing "variables can be reused"
  70. (are [final-env exprs] (let [env (calc/new-env)]
  71. (doseq [expr exprs]
  72. (calc/eval env (calc/parse expr)))
  73. (= final-env @env))
  74. {"a" 1 "b" 2} ["a = 1" "b = a + 1"]
  75. {"variable" 1 "x" 0.0} ["variable = 1 + 0 * 2" "x = log(variable)"]
  76. {"x" 1 "u" 23 "v" 24} ["x= 2 * 1 - 1 " "23 + 54" "u= 23" "v = x + u"]))
  77. (testing "variables can be rewritten"
  78. (are [final-env exprs] (let [env (calc/new-env)]
  79. (doseq [expr exprs]
  80. (calc/eval env (calc/parse expr)))
  81. (= final-env @env))
  82. {"a" 2} ["a = 1" "a = 2"]
  83. {"a" 2 "b" 2} ["a = 1" "b = a + 1" "a = b"]
  84. {"variable" 1 "x" 0} ["variable = 1 + 0 * 2" "x = log(variable)" "x = variable - 1"])))