Skip to content

Commit

Permalink
feat: add msToHumanReadableTime util fn
Browse files Browse the repository at this point in the history
  • Loading branch information
Mirasaki committed Mar 13, 2023
1 parent bfae3a2 commit ee41cd8
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ const colors = require('./config/colors.json');
const {
NS_IN_ONE_MS,
NS_IN_ONE_SECOND,
DEFAULT_DECIMAL_PRECISION
DEFAULT_DECIMAL_PRECISION,
MS_IN_ONE_DAY,
MS_IN_ONE_HOUR,
MS_IN_ONE_MINUTE,
MS_IN_ONE_SECOND
} = require('./constants');

// Resolve client configuration
Expand Down Expand Up @@ -176,6 +180,34 @@ const getRuntime = (hrtime, decimalPrecision = DEFAULT_DECIMAL_PRECISION) => {
};
};

/**
* Takes milliseconds as input and returns a string like: 2 days, 5 minutes, 21 seconds
* @param {number} ms Time in milliseconds
* @returns
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
const msToHumanReadableTime = (ms) => {
const days = Math.floor(ms / MS_IN_ONE_DAY);
const hours = Math.floor((ms % MS_IN_ONE_DAY) / MS_IN_ONE_HOUR);
const minutes = Math.floor((ms % MS_IN_ONE_HOUR) / MS_IN_ONE_MINUTE);
const seconds = Math.floor((ms % MS_IN_ONE_MINUTE) / MS_IN_ONE_SECOND);

const parts = [];
if (days > 0) parts.push(`${ days } day${ days === 1 ? '' : 's' }`);
if (hours > 0) parts.push(`${ hours } hour${ hours === 1 ? '' : 's' }`);
if (minutes > 0) parts.push(`${ minutes } minute${ minutes === 1 ? '' : 's' }`);
if (seconds > 0) parts.push(`${ seconds } second${ seconds === 1 ? '' : 's' }`);

if (parts.length === 0) return '0 seconds';
else if (parts.length === 1) return parts[0];
else if (parts.length === 2) return `${ parts[0] } and ${ parts[1] }`;
else {
const lastPart = parts.pop();
const formattedParts = parts.join(', ');
return `${ formattedParts }, and ${ lastPart }`;
}
};

module.exports = {
clientConfig,
splitCamelCaseStr,
Expand All @@ -188,5 +220,6 @@ module.exports = {
getBotInviteLink,
wait: sleep,
sleep,
getRuntime
getRuntime,
msToHumanReadableTime
};

0 comments on commit ee41cd8

Please sign in to comment.