Support modulo operator in expressions

This commit is contained in:
Zaid Abdulla committed 2021-10-25 16:51:46 -07:00
1 parent 8f662fb152
commit f24111ea9f
2 files changed
+21 -4

No files matched your search

+6 -1
View File
@@ -285,7 +285,11 @@ const lang = parsimmon.createLanguage({
.skip(parsimmon.optWhitespace), .skip(parsimmon.optWhitespace),
binaryLeft( binaryLeft(
parsimmon parsimmon
.alt(parsimmon.string("*"), parsimmon.string("/")) .alt(
parsimmon.string("*"),
parsimmon.string("/"),
parsimmon.string("%")
)
.skip(parsimmon.optWhitespace), .skip(parsimmon.optWhitespace),
parsimmon.alt( parsimmon.alt(
r.Value, r.Value,
@@ -384,6 +388,7 @@ export function stringify(exp: Expression, level = 0): string {
"-": 31, "-": 31,
"*": 32, "*": 32,
"/": 32, "/": 32,
"%": 32,
}; };
const op = exp[0].toUpperCase(); const op = exp[0].toUpperCase();
+15 -3
View File
@@ -244,9 +244,12 @@ export function evaluateCallback(exp: Expression): Expression {
} else if (exp[0] === "/") { } else if (exp[0] === "/") {
return reduce(exp, (a, b, i) => { return reduce(exp, (a, b, i) => {
if (a == null || b == null) return null; if (a == null || b == null) return null;
if (!isArray(a) && !isArray(b)) if (isArray(a) || isArray(b)) return REDUCE_SKIP;
return i === 0 ? toNumber(a) / toNumber(b) : toNumber(a) * toNumber(b); const n1 = toNumber(a);
return REDUCE_SKIP; const n2 = toNumber(b);
if (i !== 0) return n1 * n2;
if (n2 === 0) return null;
return n1 / n2;
}); });
} else if (exp[0] === "+") { } else if (exp[0] === "+") {
return reduce(exp, (a, b) => { return reduce(exp, (a, b) => {
@@ -261,6 +264,15 @@ export function evaluateCallback(exp: Expression): Expression {
return i === 0 ? toNumber(a) - toNumber(b) : toNumber(a) + toNumber(b); return i === 0 ? toNumber(a) - toNumber(b) : toNumber(a) + toNumber(b);
return REDUCE_SKIP; return REDUCE_SKIP;
}); });
} else if (exp[0] === "%") {
return reduce(exp, (a, b, i) => {
if (a == null || b == null) return null;
if (isArray(a) || isArray(b) || i !== 0) return REDUCE_SKIP;
const n1 = toNumber(a);
const n2 = Math.trunc(toNumber(b));
if (n2 === 0) return null;
return n1 % n2;
});
} else if (exp[0] === "||") { } else if (exp[0] === "||") {
return reduce(exp, (a, b) => { return reduce(exp, (a, b) => {
if (a == null || b == null) return null; if (a == null || b == null) return null;