Skip to content

Commit

Permalink
Improve sort performance.
Browse files Browse the repository at this point in the history
  • Loading branch information
cmaddox5 committed Dec 13, 2023
1 parent 4f90ec8 commit 2fdee9f
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions assets/js/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,15 +205,18 @@ export const sortByStationOrder = (
) => {
const stationOrder = STATION_ORDER_BY_LINE[filteredLine.toLowerCase()];

places.sort((placeA, placeB) => {
const indexA = stationOrder.findIndex((station) => {
return station.name.toLowerCase() === placeA.name.toLowerCase();
});
const indexB = stationOrder.findIndex((station) => {
return station.name.toLowerCase() === placeB.name.toLowerCase();
});
return indexA - indexB;
});
const stationOrderToIndex = Object.fromEntries(
stationOrder.map((station, i) => [station.name.toLowerCase(), i])
);

const placesByStationOrder = places.map((place) => ({
place,
index: stationOrderToIndex[place.name.toLowerCase()],
}));

const sortedPlaces = placesByStationOrder
.sort(({ index: i1 }, { index: i2 }) => i1 - i2)
.map(({ place }) => place);

return reverse ? places.reverse() : places;
return reverse ? sortedPlaces.reverse() : sortedPlaces;
};

0 comments on commit 2fdee9f

Please sign in to comment.