Comment by spkm
4 years ago
This! 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.
The 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.
I 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.
In his defences, he did admit at the start of the blog post that he was code golfing.