fullstacksjs / toolbox

A zero-dependency 📦 tree-shakable🌲 collection of missing JavaScript utilities.
https://toolbox.fullstacksjs.com/
MIT License
56 stars 15 forks source link

[Proposal]: format minutes into a nice time format #68

Open gooddevil79 opened 4 months ago

gooddevil79 commented 4 months ago

Function Signature

const minuteFormat = (value) => {
    const minutes = Math.trunc(value / 60);
    const seconds = value % 60;

    return `${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
};

Motivation

by using this helper function , we can easily format a minute number like 120 into " 02:00" time format. also it can be more customized and make it more reusable for any format we want by passing extra parameters

ASafaeirad commented 4 months ago

Thanks @gooddevil79 for your contribution. I'd suggest extending the function to handle hours also.

function formatTime(seconds: number): string {}

formatTime(120);    // "02:00"
formatTime(3661);   // "01:01:01"
gooddevil79 commented 4 months ago

Sure , I'll work on it

gooddevil79 commented 4 months ago
const formatTime= (value , full=false) => {
  formatValue = (val) => (val < 10 ? `0${val}` : val);
  //A : 
  if(!value) return "00:00:00" ; 

  // B :
  if(!value){
   throw new Error("Forgot to pass the value")
  }

    const hours = Math.trunc(value / 3600);
    const remainingSeconds = value % 3600;
    const minutes = Math.trunc(remainingSeconds / 60);
    const seconds = remainingSeconds % 60;

    if(full||hours>0){
      return `${formatValue(hours)}:${formatValue(minutes)}:${formatValue(seconds)}`;
    }
    return `${formatValue(minutes)}:${formatValue(seconds)}`
};

formatTime(120); // 02:00
formatTime(120,true); // 00:02:00
formatTime(); // 00:00:00  ? Error

@ASafaeirad I came up with this aproach , but I think it could be better if we could pass percies option like

const options = { hours : true, minutes : true,seconds :true}

also which aproach is good for calling it with no arguments ? A or B

ASafaeirad commented 2 months ago

What happens if we use { hours: true, minutes: false, seconds: true } 🤔

ASafaeirad commented 2 months ago

I'd suggest this signature:

format(
  seconds: number,
  format: 'hh:mm:ss' | 'hh:mm' | 'mm:ss'
): string {}