Skip to content

Commit 8e60bb2

Browse files
committed
feat: Add right-associative binary operator support
1 parent 3208900 commit 8e60bb2

File tree

4 files changed

+20
-8
lines changed

4 files changed

+20
-8
lines changed

index.ts

+15-6
Original file line numberDiff line numberDiff line change
@@ -151,15 +151,24 @@ export default class ExpressionEval {
151151
static addBinaryOp(
152152
operator: string,
153153
precedence_or_fn: number | binaryCallback,
154-
_function: binaryCallback)
154+
_ra_or_callback?: boolean | binaryCallback,
155+
_function?: binaryCallback)
155156
: void {
156-
if (_function) {
157-
jsep.addBinaryOp(operator, precedence_or_fn as number);
158-
ExpressionEval.binops[operator] = _function;
157+
let precedence, ra, cb;
158+
if (typeof precedence_or_fn === 'function') {
159+
cb = precedence_or_fn;
159160
} else {
160-
jsep.addBinaryOp(operator, ExpressionEval.DEFAULT_PRECEDENCE[operator] || 1);
161-
ExpressionEval.binops[operator] = precedence_or_fn as binaryCallback;
161+
precedence = precedence_or_fn;
162+
if (typeof _ra_or_callback === 'function') {
163+
cb = _ra_or_callback;
164+
} else {
165+
ra = _ra_or_callback;
166+
cb = _function;
167+
}
162168
}
169+
170+
jsep.addBinaryOp(operator, precedence || 1, ra);
171+
ExpressionEval.binops[operator] = cb;
163172
}
164173

165174
// inject custom node evaluators (and override existing ones)

package-lock.json

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
],
4848
"license": "MIT",
4949
"dependencies": {
50-
"jsep": "^1.1.0"
50+
"jsep": "^1.2.0"
5151
},
5252
"devDependencies": {
5353
"@commitlint/cli": "^14.1.0",

test.js

+3
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ const fixtures = [
108108
{expr: '3#4', expected: 3.4 },
109109
{expr: '(1 # 2 # 3)', expected: 1.5 }, // Fails with undefined precedence, see issue #45
110110
{expr: '1 + 2 ~ 3', expected: 9 }, // ~ is * but with low precedence
111+
{expr: '2 ** 3 ** 4', expected: 2 ** 3 ** 4},
111112

112113
// Arrow Functions
113114
{expr: '[1,2].find(v => v === 2)', expected: 2 },
@@ -202,6 +203,8 @@ expr.addBinaryOp('#', (a, b) => a + b / 10);
202203

203204
expr.addBinaryOp('~', 1, (a, b) => a * b);
204205

206+
expr.addBinaryOp('**', 11, true, (a, b) => a ** b);
207+
205208
expr.addEvaluator('TestNodeType', function(node) { return node.test + this.context.string });
206209

207210
tape('sync', (t) => {

0 commit comments

Comments
 (0)