Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/expression/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,13 @@ export const createParse = /* #__PURE__ */ factory(name, dependencies, ({
}

// check for delimiters consisting of 2 characters
if (c2.length === 2 && DELIMITERS[c2]) {
// Special case: the check for '?.' is to prevent a case like 'a?.3:.7' from being interpreted as optional chaining
// TODO: refactor the tokenization into some better way to deal with cases like 'a?.3:.7', see https://github.com/josdejong/mathjs/pull/3584
if (
c2.length === 2 &&
DELIMITERS[c2] &&
(c2 !== '?.' || !parse.isDigit(state.expression.charAt(state.index + 2)))
) {
state.tokenType = TOKENTYPE.DELIMITER
state.token = c2
next(state)
Expand Down
4 changes: 4 additions & 0 deletions test/unit-tests/expression/parse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2185,6 +2185,10 @@ describe('parse', function () {
assert.strictEqual(parseAndEval('0 > 0 ? 1 : 0 < 0 ? -1 : 0'), 0)
})

it('should parse a conditional operator and not optional chaining when followed by a number', function () {
assert.strictEqual(parseAndEval('true?.3:.7'), 0.3)
})

it('should lazily evaluate conditional expression a ? b : c', function () {
const scope = {}
math.parse('true ? (a = 2) : (b = 2)').compile().evaluate(scope)
Expand Down