Phu Tran V 2
Phu Tran V 2

Reputation: 51

How can I optimize this func and remove code line?

I have this func and how can I optimize this func using Object.keys(arr) to remove code line or get an optimization?

convertTime(diffTime): object {
    let timer = {
      days: Math.floor(diffTime / (1000 * 60 * 60 * 24)),
      hours: Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minutes: Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60)),
      second: Math.floor((diffTime % (1000 *60) /(1000))),
    }
    if (timer.days <= 9) {
      timer.days.toString() === '0' + timer.days;
    }
    if (timer.hours <= 9) {
      timer.hours.toString() === '0' + timer.hours;
    }
    if (timer.minutes <= 9) {
      timer.minutes.toString() === '0' + timer.minutes;
    }
    if (timer.second <= 9) {
      timer.second.toString() === '0' + timer.second;
    }
    return timer;
  }

Upvotes: 0

Views: 28

Answers (2)

Gilsido
Gilsido

Reputation: 572

I think the use of Object.keys() her would be:

convertTime(diffTime): object {
    let timer = {
      days: Math.floor(diffTime / (1000 * 60 * 60 * 24)),
      hours: Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
      minutes: Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60)),
      second: Math.floor((diffTime % (1000 *60) /(1000))),
    }
    Object.keys(timer).forEach(key => {
        if (timer[key] <= 9) {
            timer[key].toString() === '0' + timer[key];
        }
    });
    return timer;
}

(assuming these ifs do anything, which I doubt as @CertainPerformance commented, and I don't think that's the best solution here, @mbojko's answer is better, but it's what your colleague is looking for)

Upvotes: 0

mbojko
mbojko

Reputation: 14669

There's a function for padding strings to required length: String.prototype.padStart. Just do

    return {
      days: Math.floor(diffTime / (1000 * 60 * 60 * 24)).toString().padStart(2, '0'),
      hours: Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString().padStart(2, '0'),
      minutes: Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0'),
      second: Math.floor((diffTime % (1000 *60) /(1000))).toString().padStart(2, '0'),
    }

Upvotes: 1

Related Questions