Reputation: 31
I am currently solving the following JS challenge.
We want to display the progress that a TV show or ad has made. We have already prepared a pretty cool progressbar to display the progress. But the length of the progressbar and the duration of the shows vary. Implement the getProgress(width:int, duration:int, current:int) function that returns the position of the progressbar in pixel, px.
As an example, the function call getProgress(500, 90, 16) should return 89. Always round to the nearest whole number.
The problem here is, that I don't get the expected result 89 when I do the math. Why they expect 89 is a riddle to me...Below my code.
export function getProgress(width, duration, current) {
const currentMin = duration / 100 * current
const pixPerMin = width / duration
const currentPosition = currentMin * pixPerMin
return Math.ceil(currentPosition)
}
With my function I get 80 which should be correct - or at least I think it's correct. I am probably overlooking something or making a obvious mistake but can't see it.
Upvotes: 0
Views: 435
Reputation: 370759
The total duration is 90, and the current position is 16, so the process is around 18% complete:
console.log(16 / 90);
For a bar that's 500 pixels wide, 17.7778% of that is 88.88889 pixels:
const ratioDone = 16 / 90; // 0 to 1
console.log(500 * ratioDone);
That's where 89 comes from.
So you need:
function getProgress(width, duration, current) {
const ratioDone = current / duration;
return Math.round(ratioDone * width);
}
console.log(getProgress(500, 90, 16));
Upvotes: 3