Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add versatile duration formatting and parsing function #66

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/__tests__/duration.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import { formatOrParseDuration } from "../duration";

describe("formatOrParseDuration", () => {
describe("formatDuration", () => {
it("formats duration to hh:mm:ss", () => {
expect(formatOrParseDuration(3661000)).toBe("01:01:01");
});

it("formats duration to mm:ss", () => {
expect(formatOrParseDuration(61000, { format: "mm:ss" })).toBe("01:01");
});

it("formats duration to hh:mm", () => {
expect(formatOrParseDuration(3660000, { format: "hh:mm" })).toBe("01:01");
});

it("formats duration to DD:hh:mm:ss", () => {
expect(formatOrParseDuration(90061000, { format: "DD:hh:mm:ss" })).toBe("01:01:01:01");
});

it("formats duration to DD:hh:mm:ss:SSS", () => {
expect(formatOrParseDuration(90061001, { format: "DD:hh:mm:ss:SSS" })).toBe("01:01:01:01:001");
});

it("formats duration to hh:mm:ss,SSS", () => {
expect(formatOrParseDuration(3661001, { format: "hh:mm:ss,SSS" })).toBe("01:01:01,001");
});

it("throws error for invalid input", () => {
expect(() => formatOrParseDuration("invalid input")).toThrow("Invalid input or options.");
});
});

describe("parseDuration", () => {
it("parses hh:mm:ss to milliseconds", () => {
expect(formatOrParseDuration("01:01:01", { format: "hh:mm:ss", parse: true })).toBe(3661000);
});

it("parses mm:ss to milliseconds", () => {
expect(formatOrParseDuration("01:01", { format: "mm:ss", parse: true })).toBe(61000);
});

it("parses hh:mm to milliseconds", () => {
expect(formatOrParseDuration("01:01", { format: "hh:mm", parse: true })).toBe(3660000);
});

it("parses DD:hh:mm:ss to milliseconds", () => {
expect(formatOrParseDuration("01:01:01:01", { format: "DD:hh:mm:ss", parse: true })).toBe(90061000);
});

it("parses DD:hh:mm:ss:SSS to milliseconds", () => {
expect(formatOrParseDuration("01:01:01:01:001", { format: "DD:hh:mm:ss:SSS", parse: true })).toBe(90061001);
});

it("parses hh:mm:ss,SSS to milliseconds", () => {
expect(formatOrParseDuration("01:01:01,001", { format: "hh:mm:ss,SSS", parse: true })).toBe(3661001);
});

it("throws error for invalid duration string", () => {
expect(() => formatOrParseDuration("invalid input", { format: "hh:mm:ss", parse: true })).toThrow("Invalid duration string.");
});
});
});
87 changes: 87 additions & 0 deletions src/duration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { DurationOptions, FormatToken, DurationFormat } from './types';

/**
* Formats or parses a duration.
* @param input - Duration in milliseconds to format or a string to parse.
* @param options - Options to define formatting or parsing behavior.
* @returns A formatted duration string or duration in milliseconds.
*/
export function formatOrParseDuration(input: number | string, options: DurationOptions = {}): string | number {
const { format = 'hh:mm:ss', parse = false, locale } = options;

// Determine whether to parse or format based on the input type and options.
if (parse && typeof input === 'string') {
return parseDuration(input, format);
}

if (!parse && typeof input === 'number') {
return formatDuration(input, format);
}

throw new Error('Invalid input or options.');
}

/**
* Formats a duration given in milliseconds to a string in the specified format.
* @param durationInMs - Duration in milliseconds.
* @param format - The format string.
* @returns A string representing the duration.
*/
function formatDuration(durationInMs: number, format: DurationFormat): string {
const parts: Partial<Record<FormatToken, number>> = {
// Calculate days from milliseconds.
DD: Math.floor(durationInMs / 86400000),
// Calculate hours from remaining milliseconds.
hh: Math.floor((durationInMs % 86400000) / 3600000),
// Calculate minutes from remaining milliseconds.
mm: Math.floor((durationInMs % 3600000) / 60000),
// Calculate seconds from remaining milliseconds.
ss: Math.floor((durationInMs % 60000) / 1000),
// Calculate milliseconds.
SSS: durationInMs % 1000,
};

// Replace format tokens with corresponding values from the parts object.
return format.replace(/DD|hh|mm|ss|SSS/g, (match) => {
return String(parts[match as FormatToken]).padStart(match === 'SSS' ? 3 : 2, '0');
});
}

/**
* Parses a duration string in the specified format to milliseconds.
* @param durationString - Duration string.
* @param format - The format string.
* @returns The duration in milliseconds.
*/
function parseDuration(durationString: string, format: DurationFormat): number {
// Create a regular expression to extract the numeric values based on the format.
const regex = new RegExp(format.replace(/DD|hh|mm|ss|SSS/g, '(\\d{2,3})'));
SeanLuis marked this conversation as resolved.
Show resolved Hide resolved
const matches = durationString.match(regex);

if (!matches) {
throw new Error('Invalid duration string.');
}

// Convert the extracted numeric values to an array of numbers.
const parts = matches.slice(1).map(Number);
let durationInMs = 0;

// Calculate the total duration in milliseconds based on the format.
format.split(/[^a-zA-Z]/).forEach((part, index) => {
switch (part) {
// Add days to duration.
case 'DD': durationInMs += parts[index] * 86400000; break;
// Add hours to duration.
case 'hh': durationInMs += parts[index] * 3600000; break;
// Add minutes to duration.
case 'mm': durationInMs += parts[index] * 60000; break;
// Add seconds to duration.
case 'ss': durationInMs += parts[index] * 1000; break;
// Add milliseconds to duration.
case 'SSS': durationInMs += parts[index]; break;
default: break;
}
});

return durationInMs;
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export { addSecond } from "./addSecond"
export { ap } from "./ap"
export { applyOffset } from "./applyOffset"
export { date } from "./date"
export * from "./duration"
SeanLuis marked this conversation as resolved.
Show resolved Hide resolved
export { tzDate } from "./tzDate"
export { dayOfYear } from "./dayOfYear"
export { dayEnd } from "./dayEnd"
Expand Down
15 changes: 15 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
/**
* Possible options for formatting a duration.
*/
export type DurationFormat = "hh:mm:ss" | "mm:ss" | "hh:mm" | "DD:hh:mm:ss" | "DD:hh:mm:ss:SSS" | "hh:mm:ss,SSS" | string;

/**
* Options for formatting or parsing durations.
*/
export interface DurationOptions {
format?: DurationFormat; // supported and custom formats
parse?: boolean; // whether to parse or format
locale?: string; // future compatibility for different locales
}

/**
* The date format used as an input value. Either a date or an ISO8601 string.
*/
Expand Down Expand Up @@ -110,6 +124,7 @@ export type FormatToken =
| "A"
| "ZZ"
| "Z"
| "SSS"
SeanLuis marked this conversation as resolved.
Show resolved Hide resolved

export interface ParseOptions {
/**
Expand Down