In short, I want to be be able to output a sorted array based on provided instructions but only at a given time. I'm looking for a Javascript implementation which works more or less like the example below.
In short, I want to be be able to output a sorted array based on provided instructions but not before based on instructions. Consider the following Javascript as an example:
const list = new SortedListMechanism() // our object for processing instructions
list.insert({item: 'one'})
list.insert({item: 'four', after: 'one'})
list.insert({item: 'three', before: 'four', after:'two'})
list.insert({item:'two', after: 'one'})
list.compile()
// returns ['one', 'two', 'three', 'four']
Now, I know this is a sorting problem but I'm not quite sure what kind of sorting problem or even what to call what I'm looking for. I'm sure an NPM package exists that supports this but I honestly don't know what to look for.
As background, this is inspired by the ActiveSupport::Callback mechanism used in Django.
AuxTaco had the right idea! It is a topological sort!
Since I don't care about implementing a topological sort, I simply use the one from NPM, specifically @hapi/topo.
Here's how I use it:
const Topo = require('@hapi/topo');
let list = new Topo()
let counter= 0
list.add('one', {group:'one'}) //this package requires adding the group name so we make it the same
list.add('four', {group: 'four', after: 'one', sort: counter++})
list.add('three', {group:'three', before: 'four', after:'two', sort: counter++})
list.add('two', {group: 'two', after: 'one', sort: counter++})
list.nodes
//returns ['one', 'two', 'three', 'four']
//example from Asthmatic's comment
list = new Topo()
counter = 0
list.add('one', {group:'one', sort: counter++}) //this package requires adding the group name so we make it the same
list.add('four', {group: 'four', after: 'one', sort: counter++})
list.add('two', {group: 'two', after: 'one', sort: counter++})
list.nodes
// returns ['one', 'four', 'two']
This seems to solve the issue. Thanks!