@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
67 lines • 2.83 kB
JavaScript
/**
*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Formats a duration in milliseconds to a human-readable representation with automatic unit selection.
*
* The function selects the most appropriate time unit (milliseconds, seconds, minutes, or hours)
* based on the input value and applies smart rounding:
* - Values under 10 in a given unit are rounded to 1 decimal place
* - Values 10 or greater are rounded to whole numbers
* - Unit names are automatically pluralized based on the value
*
* @param ms - The duration in milliseconds to format. Negative or NaN values return { unit: 'seconds', value: 0 }
* @returns An object containing:
* - `unit`: The time unit string (e.g., 'second', 'seconds', 'minute', 'minutes')
* - `value`: The numeric value in the selected unit
*
* @example
* formatThinkingDuration(500) // { unit: 'milliseconds', value: 500 }
* formatThinkingDuration(1500) // { unit: 'seconds', value: 1.5 }
* formatThinkingDuration(65000) // { unit: 'minutes', value: 1.1 }
* formatThinkingDuration(3600000) // { unit: 'hour', value: 1 }
*/
export const formatThinkingDuration = (ms) => {
if (Number.isNaN(ms) || ms < 0) {
return { unit: 'seconds', value: 0 };
}
if (ms < 1000) {
const value = Math.round(ms);
const unit = value === 1 ? 'millisecond' : 'milliseconds';
return { unit, value };
}
const seconds = ms / 1000;
if (seconds < 60) {
const value = seconds < 10 ? Math.round(seconds * 10) / 10 : Math.round(seconds);
const unit = value === 1 ? 'second' : 'seconds';
return { unit, value };
}
const minutes = seconds / 60;
if (minutes < 60) {
const value = minutes < 10 ? Math.round(minutes * 10) / 10 : Math.round(minutes);
const unit = value === 1 ? 'minute' : 'minutes';
return { unit, value };
}
const hours = minutes / 60;
const value = hours < 10 ? Math.round(hours * 10) / 10 : Math.round(hours);
const unit = value === 1 ? 'hour' : 'hours';
return { unit, value };
};
//# sourceMappingURL=thinking-duration-formatter.js.map