DEV Community

saasprokit
saasprokit

Posted on

Javascript/Typescript improve performance for sorting

// 1. Decorate: Compute the heavy operation exactly ONCE per item

const decorated = items.map(item => ({
    item,
    sortKey: heavyParsingOperation(item.dateStr) // e.g., Date.parse()
}));
Enter fullscreen mode Exit fullscreen mode

// 2. Sort: Fast, lightweight numeric comparison

decorated.sort((a, b) => a.sortKey - b.sortKey);
Enter fullscreen mode Exit fullscreen mode

// 3. Undecorate: Extract original items

const sortedItems = decorated.map(entry => entry.item);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)