Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array using values from an enum?

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
like image 734
Radex Avatar asked Nov 26 '18 09:11

Radex


2 Answers

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);
like image 99
Fenton Avatar answered Nov 01 '22 23:11

Fenton


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);
});
like image 30
Cafeteru_ Avatar answered Nov 01 '22 23:11

Cafeteru_