research on implementation

the best implementation seems to be [[AST]]

suggested [[database]] structure could be:

CREATE TABLE Calculations (
    calculation_id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    expression JSON NOT NULL,
    result VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES Users(user_id)
);
INSERT INTO Calculations (user_id, expression, result)
VALUES (1, '{
  "type": "BinaryExpression",
  "operator": "-",
  "left": {
    "type": "BinaryExpression",
    "operator": "*",
    "left": { "type": "Literal", "value": 3 },
    "right": {
      "type": "BinaryExpression",
      "operator": "+",
      "left": { "type": "Literal", "value": 4 },
      "right": { "type": "Literal", "value": 5 }
    }
  },
  "right": {
    "type": "FunctionCall",
    "name": "sqrt",
    "arguments": [{ "type": "Literal", "value": 16 }]
  }
}', '23');

Running the expressions

python

from sympy import symbols, sympify

# Define the variables
x, y = symbols('x y')

# Define the expression
expression = 'x + y'

# Parse the expression
parsed_expr = sympify(expression)

# Substitute the values
result = parsed_expr.subs({x: 5, y: 3})

print(result)  # Output: 8

JS using math.js evaluate()

const math = require('mathjs');

// Define the expression and variables
const expression = 'x + y';
const variables = { x: 5, y: 3 };

// Evaluate the expression
const result = math.evaluate(expression, variables);

console.log(result);  // Output: 8

Last updated