formula-evaluator 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +118 -0
  3. package/package.json +35 -0
  4. package/src/index.js +155 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jordan Wallwork
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # formula-evaluator
2
+
3
+ A lightweight, extensible formula engine with variable tracking, nested functions, and operator precedence.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install formula-evaluator
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```js
14
+ import FormulaEvaluator from 'formula-evaluator';
15
+
16
+ const evaluator = new FormulaEvaluator();
17
+
18
+ evaluator.evaluate('1 + 2'); // 3
19
+ evaluator.evaluate('sum(1, 2, 3)'); // 6
20
+ evaluator.evaluate('upper("hello")'); // "HELLO"
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ### Constructor
26
+
27
+ Create an evaluator with an optional global context of variables:
28
+
29
+ ```js
30
+ const evaluator = new FormulaEvaluator({ tax: 0.2, basePrice: 100 });
31
+ ```
32
+
33
+ ### `evaluate(formula, localContext?)`
34
+
35
+ Evaluate a formula string and return the result. An optional local context can be passed to provide or override variables for a single evaluation.
36
+
37
+ ```js
38
+ const evaluator = new FormulaEvaluator({ x: 10 });
39
+
40
+ evaluator.evaluate('x + 1'); // 11
41
+ evaluator.evaluate('x + y', { y: 5 }); // 15
42
+ evaluator.evaluate('x', { x: 99 }); // 99 (local overrides global)
43
+ ```
44
+
45
+ ### `getDependencies(formula)`
46
+
47
+ Return an array of variable names referenced in a formula. Useful for building dependency graphs or determining which values a formula needs.
48
+
49
+ ```js
50
+ evaluator.getDependencies('x + y'); // ['x', 'y']
51
+ evaluator.getDependencies('sum(a, b, c)'); // ['a', 'b', 'c']
52
+ evaluator.getDependencies('sum(1, 2)'); // []
53
+ evaluator.getDependencies('x + x'); // ['x'] (deduplicated)
54
+ ```
55
+
56
+ ### `tokenize(formula)` / `parse(tokens)`
57
+
58
+ Lower-level methods for accessing the tokenizer and parser directly:
59
+
60
+ ```js
61
+ const tokens = evaluator.tokenize('sum(x, 1)');
62
+ const ast = evaluator.parse(tokens);
63
+ ```
64
+
65
+ ## Built-in Functions
66
+
67
+ | Function | Description | Example |
68
+ |----------|-------------|---------|
69
+ | `sum(...args)` | Sum all arguments | `sum(1, 2, 3)` → `6` |
70
+ | `avg(...args)` | Average of all arguments | `avg(2, 4, 6)` → `4` |
71
+ | `upper(str)` | Convert to uppercase | `upper("hi")` → `"HI"` |
72
+ | `join(sep, ...args)` | Join arguments with separator | `join("-", "a", "b")` → `"a-b"` |
73
+ | `if(cond, a, b)` | Conditional: returns `a` if truthy, `b` otherwise | `if(true, "yes", "no")` → `"yes"` |
74
+
75
+ ## Operators
76
+
77
+ | Operator | Description | Example |
78
+ |----------|-------------|---------|
79
+ | `+` | Addition | `1 + 2` → `3` |
80
+ | `-` | Subtraction | `5 - 3` → `2` |
81
+ | `=` | Equality check | `5 = 5` → `true` |
82
+
83
+ ## Supported Types
84
+
85
+ - **Numbers**: `42`, `3.14`, `0.5`
86
+ - **Strings**: `"hello world"`
87
+ - **Booleans**: `true`, `false`
88
+
89
+ ## Adding Custom Functions
90
+
91
+ You can extend the evaluator by adding functions directly to the `FUNCTIONS` object:
92
+
93
+ ```js
94
+ const evaluator = new FormulaEvaluator();
95
+
96
+ evaluator.FUNCTIONS.double = (x) => x * 2;
97
+ evaluator.FUNCTIONS.min = (...args) => Math.min(...args);
98
+
99
+ evaluator.evaluate('double(5)'); // 10
100
+ evaluator.evaluate('min(3, 1, 2)'); // 1
101
+ ```
102
+
103
+ ## Development
104
+
105
+ ```bash
106
+ npm install
107
+ npm test
108
+ ```
109
+
110
+ To run tests in watch mode:
111
+
112
+ ```bash
113
+ npm run test:watch
114
+ ```
115
+
116
+ ## License
117
+
118
+ MIT
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "formula-evaluator",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight formula evaluator with dependency tracking and static analysis.",
5
+ "main": "src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js"
8
+ },
9
+ "type": "module",
10
+ "files": [
11
+ "src",
12
+ "LICENSE",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "vitest run",
17
+ "test:watch": "vitest",
18
+ "prepublishOnly": "npm test"
19
+ },
20
+ "keywords": [
21
+ "formula",
22
+ "parser",
23
+ "evaluator",
24
+ "ast"
25
+ ],
26
+ "author": "Jordan Wallwork",
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/jordanwallwork/formula-evaluator.git"
31
+ },
32
+ "devDependencies": {
33
+ "vitest": "^3.0.0"
34
+ }
35
+ }
package/src/index.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * FormulaEvaluator: A lightweight, extensible formula engine
3
+ * Features: Variable tracking, nested functions, and operator precedence.
4
+ */
5
+ class FormulaEvaluator {
6
+ constructor(globalContext = {}) {
7
+ this.context = globalContext;
8
+
9
+ // Core Function Library (Easily extensible)
10
+ this.FUNCTIONS = {
11
+ upper: (str) => String(str).toUpperCase(),
12
+ join: (sep, ...args) => args.join(sep),
13
+ sum: (...args) => args.reduce((a, b) => Number(a) + Number(b), 0),
14
+ avg: (...args) => args.reduce((a, b) => a + b, 0) / args.length,
15
+ if: (cond, a, b) => (cond ? a : b),
16
+ // Internal Operator Mappings
17
+ __add: (a, b) => a + b,
18
+ __sub: (a, b) => a - b,
19
+ __eq: (a, b) => a === b,
20
+ };
21
+
22
+ this.TOKEN_TYPES = {
23
+ NUMBER: 'number',
24
+ STRING: 'string',
25
+ IDENTIFIER: 'identifier',
26
+ OPERATOR: 'operator',
27
+ DELIMITER: 'delimiter',
28
+ WHITESPACE: 'whitespace'
29
+ };
30
+ }
31
+
32
+ tokenize(str) {
33
+ const tokens = [];
34
+ const rules = [
35
+ { type: this.TOKEN_TYPES.STRING, regex: /"([^"]*)"/g },
36
+ { type: this.TOKEN_TYPES.NUMBER, regex: /\d*\.?\d+/g },
37
+ { type: this.TOKEN_TYPES.IDENTIFIER, regex: /[a-zA-Z][\w\d]*/g },
38
+ { type: this.TOKEN_TYPES.OPERATOR, regex: /[+=-]/g },
39
+ { type: this.TOKEN_TYPES.DELIMITER, regex: /[(),]/g },
40
+ { type: this.TOKEN_TYPES.WHITESPACE, regex: /\s+/g }
41
+ ];
42
+
43
+ let pos = 0;
44
+ while (pos < str.length) {
45
+ let found = false;
46
+ for (const { type, regex } of rules) {
47
+ regex.lastIndex = pos;
48
+ const match = regex.exec(str);
49
+ if (match && match.index === pos) {
50
+ if (type !== this.TOKEN_TYPES.WHITESPACE) {
51
+ tokens.push({
52
+ type,
53
+ value: type === this.TOKEN_TYPES.STRING ? match[1] : match[0],
54
+ start: pos,
55
+ end: pos + match[0].length
56
+ });
57
+ }
58
+ pos += match[0].length;
59
+ found = true;
60
+ break;
61
+ }
62
+ }
63
+ if (!found) throw new Error(`Unexpected character at ${pos}: ${str[pos]}`);
64
+ }
65
+ return tokens;
66
+ }
67
+
68
+ // --- Parser Logic ---
69
+ parse(tokens) {
70
+ let pos = 0;
71
+
72
+ const parseExpression = () => {
73
+ let node = parseToken();
74
+
75
+ const currentToken = tokens[pos];
76
+ if (currentToken && currentToken.type === this.TOKEN_TYPES.OPERATOR) {
77
+ const opToken = tokens[pos++];
78
+ const right = parseExpression();
79
+ const opMap = { '+': '__add', '-': '__sub', '=': '__eq' };
80
+ return { type: 'function', name: opMap[opToken.value], args: [node, right] };
81
+ }
82
+ return node;
83
+ };
84
+
85
+ const parseToken = () => {
86
+ const token = tokens[pos++];
87
+ if (!token) return null;
88
+
89
+ if (token.type === this.TOKEN_TYPES.NUMBER) return parseFloat(token.value);
90
+ if (token.value === 'true') return true;
91
+ if (token.value === 'false') return false;
92
+ if (token.type === this.TOKEN_TYPES.STRING) return token.value;
93
+
94
+ if (token.type === this.TOKEN_TYPES.IDENTIFIER) {
95
+ const nextToken = tokens[pos];
96
+ if (nextToken && nextToken.value === '(') {
97
+ pos++; // skip (
98
+ const args = [];
99
+ while (pos < tokens.length && tokens[pos].value !== ')') {
100
+ args.push(parseExpression());
101
+ if (tokens[pos] && tokens[pos].value === ',') pos++;
102
+ }
103
+ pos++; // skip )
104
+ return { type: 'function', name: token.value, args };
105
+ }
106
+ return { type: 'variable', name: token.value };
107
+ }
108
+
109
+ if (token.value === '(') {
110
+ const node = parseExpression();
111
+ pos++; // skip )
112
+ return node;
113
+ }
114
+ };
115
+
116
+ return parseExpression();
117
+ }
118
+
119
+ // --- Execution & Analysis ---
120
+ evaluate(formula, localContext = {}) {
121
+ const ast = this.parse(this.tokenize(formula));
122
+ const ctx = { ...this.context, ...localContext };
123
+
124
+ const run = (node) => {
125
+ if (typeof node !== 'object' || node === null) return node;
126
+
127
+ if (node.type === 'variable') {
128
+ if (!(node.name in ctx)) throw new Error(`Variable "${node.name}" not found`);
129
+ return ctx[node.name];
130
+ }
131
+
132
+ if (node.type === 'function') {
133
+ const fn = this.FUNCTIONS[node.name];
134
+ if (!fn) throw new Error(`Function "${node.name}" not found`);
135
+ return fn(...node.args.map(run));
136
+ }
137
+ };
138
+
139
+ return run(ast);
140
+ }
141
+
142
+ getDependencies(formula) {
143
+ const ast = this.parse(this.tokenize(formula));
144
+ const deps = new Set();
145
+ const walk = (node) => {
146
+ if (typeof node !== 'object' || node === null) return;
147
+ if (node.type === 'variable') deps.add(node.name);
148
+ else if (node.type === 'function') node.args.forEach(walk);
149
+ };
150
+ walk(ast);
151
+ return Array.from(deps);
152
+ }
153
+ }
154
+
155
+ export default FormulaEvaluator;