diff --git a/sort-stories.js b/sort-stories.js index d7e703e..abb905c 100644 --- a/sort-stories.js +++ b/sort-stories.js @@ -1,9 +1,70 @@ // 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 (RFC 3339 profile of ISO 8601). +const ISO_WITH_OFFSET = + /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-])(\d{2}):(\d{2}))$/; + +function daysInMonth(year, month) { + return new Date(Date.UTC(year, month, 0)).getUTCDate(); +} + +// Returns { ms, subMs } for a valid timestamp, or null if missing/invalid. +// Parsed strictly: Date.parse would silently roll over dates like Feb 30 +// and accept offset-less or non-ISO strings. +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); + const month = Number(mo); + const day = Number(d); + const hour = Number(h); + const minute = Number(mi); + const second = Number(s); + + if (month < 1 || month > 12) return null; + if (day < 1 || day > daysInMonth(year, month)) return null; + if (hour > 23 || minute > 59 || second > 59) return null; + + let offsetMinutes = 0; + if (!z) { + const offH = Number(oh); + const offM = Number(om); + if (offH > 23 || offM > 59) return null; + offsetMinutes = (sign === "+" ? 1 : -1) * (offH * 60 + offM); + } + + const fracMs = Number(`0.${frac || "0"}`) * 1000; + const wholeMs = Math.floor(fracMs); + + const utc = new Date(0); + utc.setUTCFullYear(year, month - 1, day); // avoids Date.UTC's 0–99 → 1900s mapping + utc.setUTCHours(hour, minute, second, wholeMs); + const ms = utc.getTime() - offsetMinutes * 60_000; + if (!Number.isFinite(ms)) return null; + + return { ms, subMs: fracMs - wholeMs }; +} + 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; + const keyed = stories.map((story, index) => ({ + story, + index, + instant: parseInstant(story?.published_at), + })); + + keyed.sort((a, b) => { + if (a.instant && b.instant) { + const diff = b.instant.ms - a.instant.ms || b.instant.subMs - a.instant.subMs; + if (diff !== 0) return diff; + } else if (a.instant || b.instant) { + return a.instant ? -1 : 1; // valid dates before missing/invalid ones + } + return a.index - b.index; // same instant, or both invalid: keep input order }); + + return keyed.map((k) => k.story); }