简而言之,我希望能够根据提供的指令输出排序数组,但仅在给定时间输出。我正在寻找一个 Javascript 实现,其工作方式或多或少类似于下面的示例。
简而言之,我希望能够根据提供的指令输出排序数组,但不能根据指令之前输出排序数组。以下面的 Javascript 为例:
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']
现在,我知道这是一个排序问题,但我不太确定是什么样的排序问题,甚至不太确定我正在寻找什么。我确信存在支持此功能的 NPM 包,但老实说我不知道要寻找什么。
作为背景,这是受到 Ruby on Rails 中使用的 ActiveSupport::Callback 机制的启发。
AuxTaco 的想法是正确的!这是一个拓扑排序!
由于我不关心实现拓扑排序,所以我只是使用 NPM 中的拓扑排序,特别是 @hapi/topo。
我的使用方法如下:
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']
这似乎可以解决问题。谢谢!