tc39 / proposal-extended-numeric-literals

Extensible numeric literals for JavaScript
https://tc39.github.io/proposal-extended-numeric-literals/
72 stars 18 forks source link

How does this work with arithmetic? #17

Closed kevinbarabash closed 5 years ago

kevinbarabash commented 5 years ago

It would nice to be able to do 4_px + 6_px and end up with 10_px. Looking at what _px desugars to it looks like that won't actually work. How does a person access the number itself?

littledan commented 5 years ago

Well, this proposal doesn't add operator overloading. That would be pursued separately. But I'm not sure if I understand your comment about the desugaring. What do you mean won't work?

kevinbarabash commented 5 years ago

If you set const a = 4_px. How does one access the 4 part of a? Even though this proposal doesn't support operator overloading we should still be able to do operations on these values even if it requires some unboxing and reboxing.

michaelficarra commented 5 years ago

@kevinbarabash That depends on the implementation of _px.

kevinbarabash commented 5 years ago

I should've read the proposal more closely, it looks like 3_px desugars to

_px(Object.freeze({number: 3, string: "3"}))

which means that a person should be able to do (4_px.number + 6_px.number)_px to add them.

michaelficarra commented 5 years ago

@kevinbarabash No, that is not how that would work. If the values created by _px are to be "addable", they should do it via a method. 4_px.plus(6_px). I wrote up an example in https://github.com/tc39/proposal-extended-numeric-literals/issues/11#issuecomment-379401356.

kevinbarabash commented 5 years ago

I assume the reason why my example doesn't work is the grammar requires _px to follow a numeric literal.

michaelficarra commented 5 years ago

That along with the fact that it assumes an implementation of _px along the lines of x => x.

ByteEater-pl commented 4 years ago

I assume the reason why my example doesn't work is the grammar requires _px to follow a numeric literal.

Indeed. But if those decorated numbers and bare numbers can be multiplied (seems natural), there's an easy fix: (4_px.number + 6_px.number) * 1_px.

tabatkins commented 4 years ago

No, that still requires operator overloading; currently your expression would be the same as (4 + 6) * {}, which produces NaN.

If we added operator overloading such that your expression worked, I presume we'd also allow direct same-constructor addition, so that the bare 4_px + 6_px would work as well.