Search code examples
ruby-on-railslogicprogress-bar

Unclear progress bar logic


My progress bar:

https://i.sstatic.net/wBM46.jpg

The problem:

How you can see, this is not a regular progress bar, the logic is unclear for me.

Let's say - when you have ~30 points (from 1000), you should have 50% in progress bar, but how to count this magic number?

In normal case with 30 points (from 1000) you should have around <5%.

I will happy for any clues!


Solution

  • You should calculate the progress based on PARTS, which you split. In your case, you split range to 5 parts.

    • Step 1: Find which part the current point are in. (if point is 30, it is over 2 parts - (0..3) and (3..20))
    • Step 2: Find which percentage of the point in current part (if point is 30, current part is (20..50) -> percentage = (30 - 20) / (50 - 20) = 0.333
    • Step 3: Combine them and divide the parts number.

    Sample code:

    PARTS = [(0..3), (3..20), (20..50), (50..200), (200..1000)]
    PARTS_NUMBER = PARTS.size   # 5
    
    def calculate_percentage point
      part_index = PARTS.find_index {|x| x.include?(point)}
      part = PARTS[part_index]
      remain = (point - part.first) * 1.0 / (part.last - part.first)
      (part_index + remain) / PARTS_NUMBER
    end
    
    calculate_percentage(30)  # => 0.4666666666666667
    

    Hope it helps :D