Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-55877

Javascript math on NumberDecimal should throw a clear error

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: None
    • Query Integration

      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.

            Assignee:
            backlog-query-integration [DO NOT USE] Backlog - Query Integration
            Reporter:
            david.percy@mongodb.com David Percy
            Votes:
            0 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated: