Files
otunes/lib/media-summary.ts
T

75 lines
2.1 KiB
TypeScript

function parseReleaseDate(dateString: string): Date | null {
const trimmed = dateString.trim()
if (!trimmed) {
return null
}
const isoMatch = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/)
if (isoMatch) {
const [, year, month, day] = isoMatch
const date = new Date(Number(year), Number(month) - 1, Number(day))
return Number.isNaN(date.getTime()) ? null : date
}
const dmyMatch = trimmed.match(/^(\d{2})-(\d{2})-(\d{4})$/)
if (dmyMatch) {
const [, day, month, year] = dmyMatch
const date = new Date(Number(year), Number(month) - 1, Number(day))
return Number.isNaN(date.getTime()) ? null : date
}
const yearMatch = trimmed.match(/^(\d{4})$/)
if (yearMatch) {
return new Date(Number(yearMatch[1]), 0, 1)
}
const parsed = new Date(trimmed)
return Number.isNaN(parsed.getTime()) ? null : parsed
}
export function formatReleaseDate(dateString: string): string | null {
const date = parseReleaseDate(dateString)
if (!date) {
return null
}
return date.toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
})
}
function formatTotalDurationMinutes(totalSeconds: number): string {
const totalMinutes = Math.max(1, Math.floor(totalSeconds / 60))
const hours = Math.floor(totalMinutes / 60)
const minutes = totalMinutes % 60
if (hours === 0) {
return totalMinutes === 1 ? "1 minute" : `${totalMinutes} minutes`
}
if (minutes === 0) {
return hours === 1 ? "1 hour" : `${hours} hours`
}
const hourPart = hours === 1 ? "1 hour" : `${hours} hours`
const minutePart = minutes === 1 ? "1 minute" : `${minutes} minutes`
return `${hourPart}, ${minutePart}`
}
export function formatMediaSummary(
songCount: number,
totalDurationSeconds: number
): string {
const songLabel = songCount === 1 ? "song" : "songs"
const durationLabel = formatTotalDurationMinutes(totalDurationSeconds)
return `${songCount} ${songLabel}, ${durationLabel}`
}
export function sumDurationSeconds(
items: ReadonlyArray<{ durationSeconds: number }>
): number {
return items.reduce((total, item) => total + item.durationSeconds, 0)
}