diff --git a/sort-stories.js b/sort-stories.js index d7e703e..a6cea9a 100644 --- a/sort-stories.js +++ b/sort-stories.js @@ -1,9 +1,80 @@ // 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 a ±hh:mm / ±hhmm offset. +// Strict on purpose: Date.parse also accepts offset-less strings (read as local +// time), out-of-range days like Feb 30 (silently rolled over) and free-form text. +const ISO_WITH_OFFSET = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d+))?)?(?:(Z)|([+-])(\d{2}):?(\d{2}))$/i; + +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +function daysInMonth(year, month) { + const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + return month === 2 && isLeapYear ? 29 : DAYS_IN_MONTH[month - 1]; +} + +// Returns { ms, sub } for a valid timestamp, or null if missing/invalid. +// ms is the instant in whole milliseconds since the epoch; sub holds any +// fractional-second digits beyond milliseconds, so finer precision still orders correctly. +function parseInstant(value) { + if (typeof value !== "string") return null; + const m = ISO_WITH_OFFSET.exec(value); + if (!m) return null; + + const year = Number(m[1]); + const month = Number(m[2]); + const day = Number(m[3]); + const hour = Number(m[4]); + const minute = Number(m[5]); + const second = m[6] === undefined ? 0 : Number(m[6]); + const fraction = m[7] ?? ""; + + if (month < 1 || month > 12) return null; + if (day < 1 || day > daysInMonth(year, month)) return null; + if (minute > 59 || second > 59) return null; + // 24:00[:00] is ISO 8601's "end of day" and equals 00:00 of the next day. + if (hour > 24 || (hour === 24 && (minute !== 0 || second !== 0 || /[1-9]/.test(fraction)))) return null; + + let offsetMinutes = 0; + if (!m[8]) { + const offHours = Number(m[10]); + const offMins = Number(m[11]); + if (offHours > 23 || offMins > 59) return null; + offsetMinutes = (m[9] === "-" ? -1 : 1) * (offHours * 60 + offMins); + } + + const millis = Number(fraction.slice(0, 3).padEnd(3, "0")); + // setUTCFullYear avoids Date.UTC's mapping of years 0-99 to 1900-1999. + const date = new Date(0); + date.setUTCFullYear(year, month - 1, day); + date.setUTCHours(hour, minute, second, millis); + + return { + ms: date.getTime() - offsetMinutes * 60_000, + sub: fraction.slice(3).replace(/0+$/, ""), + }; +} + +function compareInstants(a, b) { + if (a.ms !== b.ms) return a.ms - b.ms; + const len = Math.max(a.sub.length, b.sub.length); + const subA = a.sub.padEnd(len, "0"); + const subB = b.sub.padEnd(len, "0"); + return subA < subB ? -1 : subA > subB ? 1 : 0; +} + 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, instant: parseInstant(story?.published_at) })) + .sort((a, b) => { + if (a.instant && b.instant) { + const byTime = compareInstants(b.instant, a.instant); // newest first + if (byTime !== 0) return byTime; + } 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 + }) + .map((entry) => entry.story); }