HoriSun / closure-compiler

Automatically exported from code.google.com/p/closure-compiler
0 stars 0 forks source link

minify Ternary Logic when using numbers? #1215

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
When using the ternary operator `(x?:y:z)` in cases where `y` and `z` are 
numbers, we can shorten the code by applying math to `x`.

Here are some examples:
(x?3:2) to (x+2), and (x?3:0) to (3*x)

I have opened a gitHub project on this 
https://github.com/ajax333221/Ternary-Optimizer

Note: The only case where that doesn't work is whith (x?1:0) into (x), when x 
was not a number, I just need to fix that by not removing the *1 in this 
only-case scenario, I wrote the function yesterday in 7 hours.

Note2: if you guys want to use my function and the MIT license won't work, I 
would be happy to make any changes necessary to comply with that.

Original issue reported on code.google.com by myemaili...@gmail.com on 28 Jan 2014 at 7:09

GoogleCodeExporter commented 9 years ago
this doesn't work. for example, (x?3:2) to (x+2) is not a valid transformation 
for x=2

This also seems like a very narrow optimization that is not worth the 
complexity. See:
https://code.google.com/p/closure-compiler/wiki/FAQ#How_do_I_submit_a_feature_re
quest_for_a_new_type_of_optimization

Original comment by Nicholas.J.Santos on 29 Jan 2014 at 2:05

GoogleCodeExporter commented 9 years ago
OP emailed me personally, pasting the email here:

---
hello, I am not trying to make my invalid ticket reopen or something, I accept 
my feature request adds unnecessary complexity.

But just replying to "this doesn't work. for example, (x?3:2) to (x+2) is not a 
valid transformation for x=2":

is not about "x=2", it is about:

 (true ? 3:2) to (true+2) //3
 (false ? 3:2) to (false+2) //2

 (1 ? 3:2) to (1+2) //3
 (0 ? 3:2) to (0+2) //2

hard to visualize at first, but it works. 
---

Back to me: yes, agreed that this works if you assume x is a boolean and y and 
z are both numbers, which is why this case is so narrow.

Original comment by Nicholas.J.Santos on 29 Jan 2014 at 4:51

GoogleCodeExporter commented 9 years ago
[deleted comment]
GoogleCodeExporter commented 9 years ago
This is not equivalent when "x" is a string:

Given x = "a"
(x ? 2 : 3) !== (x+2)
2 !== "a2"

For this to work, x must be coerced to a numeric value.

And what's the post gzip savings? I'm guessing it's trivial even on large code 
bases.

Original comment by chadkill...@missouristate.edu on 30 Jan 2014 at 2:40

GoogleCodeExporter commented 9 years ago
you guys are right, this works on far less than I expected

Original comment by myemaili...@gmail.com on 30 Jan 2014 at 6:58