josdejong / josdejong/mathjs

Numeric keys disallowed in object expressions

Open
#3,352 10 comments 0 reactions 1 assignee Claimed by @codegiyu View on GitHub
category:expressions feature onlydust-wave
Dominant language
JavaScript
Stars
15.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
Unlike in JavaScript, numeric literals cannot be used as plain object keys.

**To Reproduce**
`math.evaluate('{0: 12-7, 1: 8+2}[2-2]')` throws `SyntaxError: Symbol or string expected as object key (char 2)`.

**Discussion**
It appears that the parser knows exactly what the situation is, which suggests there is no technical reason why this expression couldn't be allowed in the mathjs expression language. Given that it is perfectly legal in JavaScript and evaluates to 5 as expected, I would recommend that the mathjs parser be extended to accept numeric literals as object keys.

In order for this to be useful, the mathjs evaluator will also need to be extended to allow numeric values in indexing into plain objects: currently `math.evaluate('{"0": 12-7, "1": 8+2}[2-2]')` throws `TypeError: Cannot apply a numeric index as object property`

**Workaround for now**
One can convert both the keys and the index expressions to strings: `math.evaluate('{"0": 12-7, "1": 8+2}[string(2-2)]')` produces 5 as expected. But this is of course cumbersome.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.