Monday, March 2, 2020

js sort function for a fixed set of values

At work I found some code that I refactored as follows:

const ORDINAL_BY_NAME = ['5', '4', '3', '2', '1', 'No Rating'].reduce(
    (acc, name, index) => ({ ...acc, [name]: index }),

const sortFn = (a, b) => ORDINAL_BY_NAME[] - ORDINAL_BY_NAME[];

It seems a pretty ok syntax for applying an arbitrary sort order to an enum type set - like you model the desired sort by example. Probably could wrap these two lines as a function...

No comments:

Post a Comment