1

I am having trouble understanding how the below mentioned function work.

const getTime = (time) =>{
        return(
            Math.floor(time/60) + ":" + ("0" + Math.floor(time%60)).slice(-2)
        );
    };

mainly the ("0" + Math.floor(time%60)).slice(-2) part. can somebody explain this in a simple way ?

Arka
  • 957
  • 1
  • 8
  • 18
  • If the seconds part is less than 10, it adds `0`. You can assign the individual parts to a variables and verify it. `var seconds = Math.floor(time%60)` and `zeroPrefix = "0" + seconds` and then finally `zeroPrefix.slice(-2)` – adiga Mar 20 '21 at 08:08
  • 1
    This answer from the duplicate has an explanation: https://stackoverflow.com/a/12278510/3082296 – adiga Mar 20 '21 at 08:12

1 Answers1

1

As far as I understand it, the time in the brackets tells you to enter a time. For example;

const d = new Date();
const t = d.getMinutes();
console.log(t);

The main part you ask is adding the remainder of the 60th of the time you entered to 0. When we write the same code this way, if my minute is 33, we will see 34 output;

const d = new Date();
const t = d.getMinutes();
const getTime = "0" + Math.floor(t%60);
getTime.slice(-2);
console.log(t);

**Edit: An alternative**
You're looking at the `remainder operator` and the `slice method`.

Whenever code is confusing, it can help to break it up into named pieces and print them. This snippet does just that:

// Tests
formattedMinsAndSecs(5);
formattedMinsAndSecs(3611);
formattedMinsAndSecs(999999);


// Reworked function
function formattedMinsAndSecs(seconds){

  console.log("input:", seconds);

  const minsPart = Math.floor(seconds / 60);
  console.log("minsPart:", minsPart);

  // Remainder operator (%) gets remainder after division
  const secsPart = Math.floor(seconds % 60); 
  console.log("secsPart:", secsPart);

  const withLeadingZero = "0" + secsPart;
  console.log("withLeadingZero:", withLeadingZero);

  // slice method with 1 negative argument gets last N chars
  const lastTwoCharacters = withLeadingZero.slice(-2);
  console.log("lastTwoCharacters:", lastTwoCharacters);

  const formatted = minsPart + ":" + lastTwoCharacters
  console.log("formatted:", formatted, "\n\n");

  return formatted;
};
Cat
  • 4,141
  • 2
  • 10
  • 18
Ali Öner
  • 11
  • 2
  • @AjeetShah, thanks for providing input. I cleaned up a bit and updated the edit text. The links keep breaking, and I haven't been able to figure out why so I just removed them for now. (I thought about doing a separate question, but I feared that if folks disliked the original question enough to close it, that a new one wouldn't fare any better.) – Cat Mar 20 '21 at 09:33