Skip to content
Snippets Groups Projects
Commit 836a35d6 authored by Bernard Roland (Student Com20)'s avatar Bernard Roland (Student Com20)
Browse files

Added a simple formater for durations

parent 2661d014
No related branches found
No related tags found
No related merge requests found
import { formatDate, formatTime, formatDuration, formatRelativeTime, addTime, subtractTime } from 'timely';
import {
formatDate,
formatTime,
formatDuration,
formatRelativeTime,
formatSimpleDuration,
addTime,
subtractTime,
} from 'timely';
test('simple duration format works as expected', () => {
expect(formatSimpleDuration(1.5 * 60 * 1000)).toEqual('01:30');
});
test('simple duration format can include hours', () => {
expect(formatSimpleDuration(5 * 60 * 60 * 1000 + 42.5 * 60 * 1000, true)).toEqual('05:42:30');
});
test('simple duration format can include milliseconds', () => {
expect(formatSimpleDuration(12345, false, false, true, true)).toEqual('12.345');
});
test('small durations format as `moments`', () => {
expect(formatDuration(10 * 1000)).toEqual('moments');
......
......@@ -35,6 +35,46 @@ export function formatDuration(millis: number, precision: Unit = 'minute'): stri
return 'moments';
}
function formatNumber(value: number, places = 2, padding = '0'): string {
let result = Math.floor(value).toString();
while (result.length < places) {
result = padding + result;
}
return result;
}
export function formatSimpleDuration(millis: number, hours = false, minutes = true, seconds = true, milliseconds = false): string {
let result = '';
if (hours) {
const hour = Math.floor(millis / UNITS['hour']);
millis -= hour * UNITS['hour'];
result += formatNumber(hour);
}
if (minutes) {
if (result.length !== 0) {
result += ':';
}
const min = Math.floor(millis / UNITS['minute']);
millis -= min * UNITS['minute'];
result += formatNumber(min);
}
if (seconds) {
if (result.length !== 0) {
result += ':';
}
const sec = Math.floor(millis / UNITS['second']);
millis -= sec * UNITS['second'];
result += formatNumber(sec);
}
if (milliseconds) {
if (result.length !== 0) {
result += '.';
}
result += formatNumber(millis, 3);
}
return result;
}
function formatOrdinal(value: number): string {
value = Math.floor(value);
if (value === 1 || (value % 10 === 1 && value > 20)) {
......@@ -48,14 +88,6 @@ function formatOrdinal(value: number): string {
}
}
function formatNumber(value: number, places = 2, padding = '0'): string {
let result = Math.floor(value).toString();
while (result.length < places) {
result = padding + result;
}
return result;
}
const MONTHS = [
'January',
'February',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment