I want to sort elements of an array using an enum, I would like to know how to do it, I have tried with a switch
statement with no success.
const enum Order {
Start = 'Start',
Run = 'Run',
End = 'End',
}
const predicate (a, b) => // TODO
const data = [Order.End, Order.Run, Order.Start]
const result = data.sort(predicate)
// wanted result is: // Start, Run, End
Normally with an enum, the value is already comparable.
const enum Order {
Start = 0,
Run = 1,
End = 2,
}
const data = [Order.End, Order.Run, Order.Start];
const result = data.sort();
console.log(result);
A non-constant enum can even be mapped to the string values, as shown here:
enum Order {
Start = 0,
Run = 1,
End = 2,
}
const data = [Order.End, Order.Run, Order.Start];
const result = data.sort();
console.log(result.map((val) => Order[val]));
But in your case, you could convert them into an easily sortable value if necessary (assuming you desire to avoid alphabetical ordering).
const enum Order {
Start = 'Start',
Run = 'Run',
End = 'End',
}
const predicate = (a, b) => {
const map = {};
map[Order.Start] = 1;
map[Order.Run] = 2;
map[Order.End] = 3;
if (map[a] < map[b]) {
return -1;
}
if (map[a] > map[b]) {
return 1;
}
return 0;
}
const data = [Order.End, Order.Run, Order.Start];
const result = data.sort(predicate);
console.log(result);
I created a function in typescript based on previous answer to order objects from an enum.
export function sortByStatus(a: Element, b: Element): number {
const map = new Map<Status, number>();
map.set(Status.DONE, 0);
map.set(Status.ERROR, 1);
map.set(Status.PROCESSING, 2);
map.set(Status.NONE, 3);
if (map.get(a.status) < map.get(b.status)) {
return -1;
}
if (map.get(a.status) > map.get(b.status)) {
return 1;
}
return 0;
}
Furthermore, I include a mini test to check its functionality.
it('check sortByStatus', () => {
expect(sortByStatus(a, b)).toBeLessThanOrEqual(1);
expect(sortByStatus(b, a)).toBeGreaterThanOrEqual(-1);
expect(sortByStatus(a, a)).toBe(0);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With