diff --git a/sort-stories.js b/sort-stories.js index d7e703e..35b617a 100644 --- a/sort-stories.js +++ b/sort-stories.js @@ -1,9 +1,47 @@ // 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[.fff…]](Z|±HH:MM). The UTC offset is 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 published_at, or null if missing/invalid. +// Date.parse is not used directly: it accepts impossible dates (e.g. Feb 30), +// offset-less strings (interpreted as local time) and non-ISO formats. +function parseInstant(value) { + if (typeof value !== "string") return null; + const m = ISO_WITH_OFFSET.exec(value.trim()); + if (!m) return null; + const [, y, mo, d, h, mi, s = "0", frac = "", z, sign, oh, om] = m; + const year = +y, month = +mo, day = +d, hour = +h, minute = +mi, second = +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) { + if (+oh > 23 || +om > 59) return null; + offsetMinutes = (sign === "-" ? -1 : 1) * (+oh * 60 + +om); + } + const ms = Number((frac + "000").slice(0, 3)); + const local = Date.UTC(year, month - 1, day, hour, minute, second, ms); + // Date.UTC maps years 0–99 to 1900–1999; correct for that. + const utc = new Date(local); + if (year < 100) utc.setUTCFullYear(year); + const t = utc.getTime() - offsetMinutes * 60_000; + return Number.isFinite(t) ? t : null; +} + 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; - }); + 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 !== b.time) return a.time === null ? 1 : -1; + } else if (a.time !== b.time) { + return b.time - a.time; + } + return a.index - b.index; + }) + .map((entry) => entry.story); }