5 ms·
> At the very least, the loop based code could be cleaned up significantly. Seems like the loop based code wasn't so bad after all...
by bla3 5y ago
> At the very least, the loop based code could be cleaned up significantly.
Seems like the loop based code wasn't so bad after all...
- meetups323 5y agoLoop code has the same bug.
- bla3 5y agoThis is Java, not JavaScript. The exponents table was likely of integer type. Then it works.
- alisonkisk 5y agoHow does that avoid the misrounding bug for 999,999B = 1000KB (wrong), 1MB correct?
- bla3 5y agoD'oh, you're right.
- spkm 5y agoThis! If I had to choose between the two snippets I would have taken the loop based one without a second though, because of its simplicity. The second snippet is what usually happens when people try to write "clever" code.
- dataflow 5y agoThe loop by itself isn't entirely clear on what it's doing. Stuff like the direction of the > comparison and what to do vs. >= and the byteCount / magnitudes[i] at the end really do require you to pause & do mental analysis to check correctness. I think the real solution here is to define an integer log (ilog()?) function based on division and use that in the same manner as the log(). That way you only do do the analysis the first time you write that function, and after that you just call the function knowing that it's correct.
- bigiain 5y agoIn his defences, he did admit at the start of the blog post that he was code golfing.
- jmelloy 5y agoI was reading this and thought it sounded familiar. A few months ago I needed a human readable bytes format, ended up on that stack overflow article and, plot twist, copied the while loop one.
- twobitshifter 5y agoPremature optimization strikes again.