/** * Converts a time string (e.g., "1d2h3m4s") into milliseconds or seconds * @param {string} timeStr - The time string to convert (e.g., "1d2h3m4s") * @param {boolean} [inSeconds=false] - If true, returns result in seconds instead of milliseconds * @returns {number} The converted time in milliseconds or seconds */ function dhms(timeStr, inSeconds = false) { // Return 0 for invalid input if (typeof timeStr !== 'string' || !timeStr.trim()) { return 0; } // Define time unit multipliers const multipliers = { s: inSeconds ? 1 : 1000, m: inSeconds ? 60 : 60000, h: inSeconds ? 3600 : 3600000, d: inSeconds ? 86400 : 86400000 }; // Remove whitespace and split into parts const cleanStr = timeStr.replace(/\s/g, ''); // Extract the numeric value at the end (if any) const tailMatch = cleanStr.match(/-?\d+$/); const tailValue = tailMatch ? parseInt(tailMatch[0], 10) : 0; // Extract and convert time parts const timeParts = (cleanStr.match(/-?\d+[^-0-9]+/g) || []) .map(part => { const value = parseInt(part.replace(/[^-0-9]+/g, ''), 10); const unit = part.replace(/[-0-9]+/g, ''); return value * (multipliers[unit] || 0); }); // Sum all parts including the tail return [tailValue, ...timeParts].reduce((sum, value) => sum + value, 0); } module.exports = dhms;