diff --git a/sort-stories.js b/sort-stories.js index d7e703e..0919bb6 100644 --- a/sort-stories.js +++ b/sort-stories.js @@ -1,9 +1,49 @@ // Sort synthetic news stories newest first by their publication time. // A story is { id, title, published_at }, where published_at is an ISO 8601 timestamp with an explicit UTC offset. + +// YYYY-MM-DDTHH:MM[:SS[.fraction]] followed by Z or ±HH:MM (offset required). +const ISO_WITH_OFFSET = + /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-])(\d{2}):(\d{2}))$/; + +// Returns epoch milliseconds for a valid timestamp, or null for missing/invalid input. +function parseInstant(value) { + if (typeof value !== "string") return null; + const m = ISO_WITH_OFFSET.exec(value); + if (!m) return null; + + const [, y, mo, d, h, mi, s = "0", frac = "", z, sign, oh, om] = m; + const year = Number(y), month = Number(mo), day = Number(d); + const hour = Number(h), minute = Number(mi), second = Number(s); + + if (month < 1 || month > 12) return null; + const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate(); + if (day < 1 || day > daysInMonth) return null; + if (hour > 23 || minute > 59 || second > 59) return null; + + let offsetMinutes = 0; + if (!z) { + const offH = Number(oh), offM = Number(om); + if (offH > 23 || offM > 59) return null; + offsetMinutes = (sign === "-" ? -1 : 1) * (offH * 60 + offM); + } + + const ms = frac ? Number(frac.slice(0, 3).padEnd(3, "0")) : 0; + // Date.UTC maps years 0-99 to 1900-1999; setUTCFullYear avoids that. + const date = new Date(Date.UTC(2000, month - 1, day, hour, minute, second, ms)); + date.setUTCFullYear(year); + return date.getTime() - offsetMinutes * 60_000; +} + export function sortStoriesNewestFirst(stories) { - return stories.slice().sort((a, b) => { - if (a.published_at < b.published_at) return 1; - if (a.published_at > b.published_at) return -1; - return 0; - }); + // Parse each timestamp once; Array.prototype.sort is stable, so ties keep input order. + return stories + .map((story, index) => ({ story, index, time: parseInstant(story?.published_at) })) + .sort((a, b) => { + if (a.time === null || b.time === null) { + if (a.time === null && b.time === null) return a.index - b.index; + return a.time === null ? 1 : -1; + } + return b.time - a.time || a.index - b.index; + }) + .map((entry) => entry.story); }