diff --git a/sort-stories.js b/sort-stories.js index d7e703e..830494d 100644 --- a/sort-stories.js +++ b/sort-stories.js @@ -1,9 +1,18 @@ // 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. 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) => ({ + story, + timestamp: typeof story.published_at === 'string' + ? Date.parse(story.published_at) + : NaN, + })) + .sort((a, b) => { + if (Number.isNaN(a.timestamp)) return Number.isNaN(b.timestamp) ? 0 : 1; + if (Number.isNaN(b.timestamp)) return -1; + // Stable sorting preserves input order for equal instants and invalid dates. + return b.timestamp - a.timestamp; + }) + .map(({ story }) => story); }