I want to sort an array based on "before" and "after" conditions.
Example:
- C
should be before B
: Example:{key: 'C', condition: {$before: 'B'}
- B
should be after A
: Example:{key: 'B', condition: {$after: 'A'}
- A: Example
{key: 'A'}
.
The resulting sorted list would be: A, C, B
.
I need this so I can sort a list of middleware in a pipeline. Each middleware has a condition and I should come up with an order in which all conditions from all middleware are met. This is similar to what MS Project
does to organize tasks in a Gantt given what are the requirements for a task.
Question: What is the easiest way to achieve it? Even by using external libraries like underscore
? Bonus: Does this kind of sorting have a name better than "conditional sorting"? That would help on my Google searches.
EDIT: The input should be an array of items with their conditions. I can't hardcode the sort method.
EDIT 2: As @Berdi stated. This is called typological sorting. Yes, depending on the items and conditions, there might be no combination that meet all the conditions and my algorithm should trigger an exception.
EDIT 3: The way I'm thinking of implementing this is calculating all the possible combinations and then look for the first one that meet all the conditions. This may not be terribly slow for me because, in my case, I can do this just once when the app starts and I'm not going to have more than 50 items in the array. But anyway, for the science, it would be good to know a more optimized solution.
EDIT 4: I would accept a solution that works with after conditions only. Like MS Project
.