Ranking order of time

Asked

Viewed 74 times

0

I’m developing a game that performs a function in Javascript that clocks how long it took the player to finish to reach the last stage:

function formatatempo(segs) {
    var min = 0;
    va hr = 0;

    while (segs >= 60) {
        if (segs >= 60) {
            segs = segs - 60;
            min = min + 1;
        }
    }

    while (min >= 60) {
        if (min >= 60) {
            min = min - 60;
            hr = hr + 1;
        }
    }

    if (hr < 10) {
        hr = "0" + hr
    }
    if (min < 10) {
        min = "0" + min
    }
    if (segs < 10) {
        segs = "0" + segs
    }
    fin = hr + ":" + min + ":" + segs
    return fin;
}

In the above case, at the end of the execution the variable fin is returned with time travelled. The problem, is that I need to store these outputs in a ranking, how could I sort them in a way that takes from the smallest to the longest time?

  • If you return the results in timestamp is very easy to sort, just bring from the smallest to the largest.

  • the problem is that I am not able to slice the variable I took from JS and passed PHP into an array : $fin = "<script>Document.write(fin)</script>"; the function explodes from PHP does not accept this,

  • Dude this is Javascript, not php, you have to know the difference between the two. In addition, the javascript language is client-side only and not server-side.

2 answers

0

You just want to take the amount of seconds the guy spent and display it in a legible way, right? Like, if I spent 65 seconds solving, you want to show that I spent 00:01:05 correct? Ever thought about doing so:

function foo($seconds) {
  $t = round($seconds);
  return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}

echo foo('290.52262423327'), "\n";
echo foo('9290.52262423327'), "\n";
echo foo(86400+120+6), "\n";

returns

00:04:51
02:34:51
24:02:06

0

On the line fin = hr + ":" + min + ":" + segs of this function, you ensure that the return of this function is a string, in the form HH:MM:SS; then you can make a direct string comparison to do the Sort, using the function locationCompare() and the Sort.

Follow an example fiddle: https://jsfiddle.net/pv4ojgp2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.