codewars (no if :D )

mail@pastecode.io avatar
unknown
typescript
2 years ago
1.2 kB
2
Indexable
Never
const YEAR = 31536000;
const DAY = 86400;
const HOUR = 3600;
const MINUTE = 60;

function generateLabel(amount: number, singularLabel: string): string {
  if (!amount) {
    return null;
  }

  return `${amount} ${singularLabel}${amount > 1 ? 's' : ''}`;
}

function filterExisting<K>(array: (K | null)[]): K[] {
  return array.filter((x) => x);
}

function toHumanlyReadable(duration: number): string {
  if (!duration) {
    return 'now';
  }

  const years = Math.floor(duration / YEAR);
  const days = Math.floor((duration - years * YEAR) / DAY);
  const hours = Math.floor((duration - years * YEAR - days * DAY) / HOUR);
  const minutes = Math.floor(
    (duration - years * YEAR - days * DAY - hours * HOUR) / MINUTE
  );
  const seconds =
    duration - years * YEAR - days * DAY - hours * HOUR - minutes * MINUTE;
  const resultArray = filterExisting([
    generateLabel(years, 'year'),
    generateLabel(days, 'day'),
    generateLabel(hours, 'hour'),
    generateLabel(minutes, 'minute'),
    generateLabel(seconds, 'second'),
  ]);
  const firstPart = resultArray.slice(0, -1).join(', ');
  const secondPart = resultArray.slice(-1);

  return filterExisting([firstPart, secondPart]).join(' and ');
}