[SERVER-55877] Javascript math on NumberDecimal should throw a clear error Created: 07/Apr/21  Updated: 03/Feb/24

Status: Backlog
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: David Percy Assignee: Backlog - Query Integration
Resolution: Unresolved Votes: 0
Labels: qi-javascript
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Query Integration
Participants:

 Description   

Javascript math operators don't produce useful results when applied to NumberDecimal:

> NumberDecimal(2) + 2
NumberDecimal("2.00000000000000")2
> NumberDecimal(2) - 2
NaN

This is especially confusing in server-side Javascript, like $function.

We could make it fail more helpfully by customizing the toPrimitive method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive):

> NumberDecimal.prototype[Symbol.toPrimitive] = () => { throw "Invalid..."; }
() => { throw "Invalid..."; }
> NumberDecimal(2) + 2
uncaught exception: Invalid...
> NumberDecimal(2) - 2
uncaught exception: Invalid...

toString would still work as expected, even if we customize toPrimitive:

> NumberDecimal(2)
NumberDecimal("2.00000000000000")
> NumberDecimal(2).toString()
NumberDecimal("2.00000000000000")

But implicit coercion to string would stop working:

> NumberDecimal(2) + " items"
uncaught exception: Invalid...
> `${NumberDecimal(2)} items`
uncaught exception: Invalid...

which could be good or bad. It can reveal mistakes, but can also break tests or scripts that intentionally use this behavior.



 Comments   
Comment by Xiaochen Wu [ 22/Mar/23 ]

Suggest to add to QO quick win candidate.

Comment by Joe Kanaan [ 08/Apr/21 ]

Hi kateryna.kamenieva , do you think this is worth changing?

Comment by Katya Kamenieva [ 08/Apr/21 ]

Also, if you just pass NumberDecimal into function and return it as is, you'll get {}.

Generated at Thu Feb 08 05:37:43 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.