base.spec.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import {
  2. BinaryOperation,
  3. BinaryOperators,
  4. evaluate,
  5. } from "../src";
  6. describe("Simple expression tests", () => {
  7. test("Check literal value", () => {
  8. expect(evaluate({ type: "literal", value: 5 })).toBeCloseTo(5);
  9. });
  10. test("Check addition", () => {
  11. const expr: BinaryOperation = bin("+", 5, 10);
  12. expect(evaluate(expr)).toBeCloseTo(15);
  13. });
  14. test("Check subtraction", () => {
  15. const expr: BinaryOperation = bin("-", 5, 10);
  16. expect(evaluate(expr)).toBeCloseTo(-5);
  17. });
  18. test("Check multiplication", () => {
  19. const expr: BinaryOperation = bin("*", 5, 10);
  20. expect(evaluate(expr)).toBeCloseTo(50);
  21. });
  22. test("Check division", () => {
  23. const expr: BinaryOperation = bin("/", 10, 5);
  24. expect(evaluate(expr)).toBeCloseTo(2);
  25. });
  26. });
  27. function bin(op: BinaryOperators, x: number, y: number): BinaryOperation {
  28. return {
  29. left: {
  30. type: "literal",
  31. value: x,
  32. },
  33. operator: op,
  34. right: {
  35. type: "literal",
  36. value: y,
  37. },
  38. type: "binary",
  39. };
  40. }