Hacker News new | ask | show | jobs
by kwhitefoot 1248 days ago
It has almost twice as many comparisons as necessary. The term to the left of each AND is redundant because it has already been checked by the preceding IF. It also does not guard against negative arguments. Perhaps the environment in which it is used guarantees that negative arguments cannot occur.

If I were reviewing this code I would at least ask the developer to add an assertion or contract requiring that the argument be in the inclusive range [0..1]

The choice of variable name, percentage, is also misleading. At least I suspect it is because I would expect the comparisons involving percentages to be to numbers between 0 and 100.

If lack of allocations is a requirement then one could create a static array of strings and use

    int(percent * 10)
as the index. This would eliminate all of the comparisons and also throw an index out of range (in any sane language) if the value was outside the allowed range.
2 comments

If you have int(percent * 10) + 1 you can just generate that many blue circles (checking for the edge-case of zero, or even better using ceil instead of int), the rest white and return it - no need for manually crafting the array (since the performance is, I presume, not a critical thing here). If tomorrow you want stars instead of the circles you just edit 2 chars in one place, instead of typing manually all combinations.
The compile time allocated array is to avoid allocations at run time, if that is a requirement. In a language with proper macros such as Nim or Lisp this can be done at compile time using exactly your approach. That way it executes fast and is just as simple .
I've been looking into nim lately (just for fun with the Advent of Code problems) and it looks fantastic. I plan to allocate more time to it in future definitely.
Find-and-replace exists.

Having a separate string for each level of progress also lets you do other kinds of customizations: you could have a rainbow progress bar, or put little bits of encouraging text to the right of the progress bar, like "Almost there!" at 90%.

Essentially, you're making one type of customization (i.e., changing the symbols) slightly easier, at the expense of making other types of customization harder.

You know it's only a matter of time before someone dissects each one of your objections. In fact you could do so yourself with a bit of a wider perspective.
How long do I need to wait?
I think they're all great suggestions (albeit for such a tiny, irrelevant piece of code). The only problem I can think of is that the given code rounds up, but your suggestion of `int(percent * 10)` rounds down.
It's just too obvious. The metrics you're optimizing for don't matter to any of the stakeholders.