Evaluating spreadsheet formulas in JavaScript: from new Function to an AST limited to arithmetic

June 23, 2025

目标值=(n1+n2)/c1 (“target value = …”) was an example I used while building a data quality assessment tool for a hospital. The formula was already written, and each of its three variables had a SQL query to fetch its value. Could the program simply calculate what the line said? Then colleagues adjusting a metric definition could change the formula, click Calculate, and see the result immediately as long as the necessary numbers had already been queried.

Why can’t I calculate the ratio after reading the Excel file?

The workbook had columns labeled “变量名” (variable name), “sql语句” (SQL statement), and “医院项目比值公式” (hospital project ratio formula). The last column held text. Here n1 was a name we assigned to a query result. It looks like an Excel cell reference, but reading the whole sheet won’t tell you its value. That comes only after the corresponding SQL runs.

On June 13 I looked up how to read XLSX files in Go. In “用Go读写Excel(XLSX)文件” (“Reading and writing Excel files with Go”), republished by 后端之巅, Excelize used GetCellValue for one cell and GetRows for a whole sheet. I then searched for Excelize and opened its repository. That afternoon I also read the govaluate documentation, which put the two steps of evaluation neatly: “You create a new EvaluableExpression, then call "Evaluate" on it.” Supply the formula when creating the expression, then supply the variable values when calling Evaluate.12

I later realized JavaScript suited me better for this tool, so I used it for both reading and calculation. The web page read Excel with SheetJS’s xlsx npm package. I had committed the sheet-reading code by June 22. The next morning, I asked Cursor how to complete parseXlsxToJson with a browser-compatible library, and the response used xlsx too. I also searched for xlsx js library and opened the npm package page that day. The three lines below are from the June 22 frontend. data contains the bytes the browser read from the file.3

const workbook = XLSX.read(data, { type: 'array' });
const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = XLSX.utils.sheet_to_json(firstSheet);

We can now use row['变量名'] and row['sql语句'] to read each row’s mapping. The frontend combines duplicate SQL statements so the backend needs to run each query only once. I covered when to send the remaining queries in Limiting concurrent batch SQL queries with a semaphore. For each metric, match query values back to variable names within the same project. Suppose this run returned n1 = 5, n2 = 6, and c1 = 11. Now we have both inputs to evaluation: the original formula and this run’s variable values.

How did quickEval turn the string into 1?

On June 17 I first added formula evaluation to the level5sql Node.js script. By June 23 the management tool’s web page also used the calculation endpoint. The Node service read the text from “医院项目比值公式” and passed it to quickEval with the project’s variables. The Go version could read the formula text, run each SQL statement, and store the variable values. A later Python service could manage SQL and formula definitions. The code that actually computed a number from the formula was JavaScript.4

When I asked Cursor how to collect the variables used in one formula, the selected quickEval already contained the new Function line. Next I wanted to handle the spreadsheet’s two conventions: some formulas put “目标值” on the left of the equals sign and some on the right. How could I extract the arithmetic in either case? Follow the three example numbers through the preserved implementation to see how it handled a label on the left.

表格文本        目标值=(n1+n2)/c1
取等号右边      (n1+n2)/c1
替换变量后      ((5)+(6))/(11)
求值结果        1

The function first normalized full-width parentheses to ASCII parentheses. After substituting the variables, only the last line remained:

return new Function(`return ${code}`)();

new Function compiles the body into a function, and the final () calls it immediately. That gives us existing rules such as evaluating parentheses before division. It also exposes the cost: Function accepts a JavaScript function body, while the spreadsheet author only needs a few arithmetic operations. Even after the variable names are replaced by numbers, the remaining characters are interpreted as JavaScript syntax.5

The old code also had a problem that was easier to hit in everyday use. When assembling variables, the calculation endpoint used sqlResults[sqlId] || 0. If the query value for n2 were missing, the example ratio could quietly become 5/11. That looks just like a valid metric. During review I’d much rather see “missing n2” so I know which SQL query to revisit.4

Do I need to write a parser to allow only the four arithmetic operations?

Looking back, I’d keep the spreadsheet notation and separate recognizing a formula from calculating its value. First extract the arithmetic according to the sheet’s conventions. For example, allow a standalone expression or one prefixed with the fixed label 目标值=, and normalize full-width parentheses. Report unfamiliar forms with a row number. Casually deleting a character might turn a mistyped formula into a different formula that still evaluates.

An existing parser will do. Babel’s parseExpression, for example, can turn (n1+n2)/c1 into an abstract syntax tree (AST). Division is at the root, with n1+n2 on the left and variable c1 on the right. The tree’s shape already captures what the parentheses mean. Evaluate from the bottom up, looking up each variable in this run’s query results and checking the denominator when you reach division.6

Here’s an educational example I rewrote today. It runs in a Node.js project with @babel/parser installed. It takes the arithmetic part after extraction and evaluates only finite numbers, registered variables, and four binary operations. Other nodes, including function calls and property access, produce errors. Put only successfully queried, numeric values into the Map.

const { parseExpression } = require('@babel/parser');

function finite(value) {
  if (!Number.isFinite(value)) throw new Error('需要有限数值');
  return value;
}

function evaluate(node, values) {
  if (node.type === 'NumericLiteral') return finite(node.value);
  if (node.type === 'Identifier') {
    if (!values.has(node.name)) throw new Error(`缺少变量 ${node.name}`);
    return finite(values.get(node.name));
  }
  if (node.type !== 'BinaryExpression') throw new Error('不支持这种表达式');

  const left = evaluate(node.left, values);
  const right = evaluate(node.right, values);
  switch (node.operator) {
    case '+': return finite(left + right);
    case '-': return finite(left - right);
    case '*': return finite(left * right);
    case '/':
      if (right === 0) throw new Error('分母为零');
      return finite(left / right);
    default: throw new Error(`不支持运算符 ${node.operator}`);
  }
}

const formula = parseExpression('(n1+n2)/c1');
const values = new Map([['n1', 5], ['n2', 6], ['c1', 11]]);
console.log(evaluate(formula, values)); // 1

I’d test the code with three deliberately chosen datasets. If both numerator queries return zero and the denominator is 11, the result should be 0. If n2 is missing, the error should name it. If all three queries succeed but c1 is zero, the result should say the ratio is undefined. Filling in zero for the last two cases might make the sheet look tidier, but it would deprive reviewers of evidence.

The page my colleagues used had two buttons: Execute SQL and Calculate. The first button’s records answered “Where did these numbers come from?” The second button’s formula answered “How do they produce the metric?” When reviewing a ratio, we could change just the formula and recompute it from the same numbers, or follow a variable back to the original SQL. The interface and how we deployed it on Windows 7

Footnotes

  1. 后端之巅. (2022, June 30). 用Go读写Excel(XLSX)文件(转载 Ri Xu 的 DZone 教程,“读取一个XLSX文件”节). 稀土掘金. 掘金文章。Xu, R. (2021, July 30). Read and write Excel (XLSX) files with Go(Reading an XLSX File). DZone. 原文。Excelize contributors. (n.d.). Excelize. GitHub. 当时访问的仓库。 ↩

  2. govaluate contributors. (n.d.). govaluate(README, “How do I use it?”, para. 1). Go Packages. 当时读到的包文档。Knetic. (n.d.). govaluate. GitHub. 项目 README。 ↩

  3. CaiBorui [S2thend]. (2025, June 22). Add feature parse xlsx [本地 Git 提交 8e12efb]. SqlQueryManagement, webui/src/App.jsx. SheetJS. (n.d.). xlsx. npm. 当时打开的包页面。SheetJS. (2026, August 3). Arrays of data(Array Output). SheetJS Documentation. sheet_to_json。 ↩

  4. CaiBorui [S2thend]. (2025, June 17). Add function to calculate query result from variable results in queries object [本地 Git 提交 0ae92fe]. level5sql, calcProc.js. CaiBorui [S2thend]. (2025, June 23). Add API for calculate results [本地 Git 提交 a30300e]. SqlQueryManagement, server-js/main.js、server-js/utils/calc-eval.js。 ↩ ↩2

  5. MDN contributors. (n.d.). Function() constructor(Description). MDN Web Docs. 动态构造函数的语义。 ↩

  6. Babel contributors. (n.d.). @babel/parser(API, parseExpression). Babel. 单个表达式的解析接口。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-23). Evaluating spreadsheet formulas in JavaScript: from new Function to an AST limited to arithmetic. https://caiborui.com/blog/2025-06-23-zh-javascript-spreadsheet-formula-evaluation-entrans

@misc{borui2025-67516582,
  author = {borui},
  title = {{Evaluating spreadsheet formulas in JavaScript: from new Function to an AST limited to arithmetic}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-23-zh-javascript-spreadsheet-formula-evaluation-entrans}
}