Search code examples
javascriptarrayssortingdoubly-linked-listramda.js

Sort doubly linked list by next id Ramda.js


I want to sort doubly linked list by next_id value.

My DLL:

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

As a result:

const dll_result = [
  {id: '14', prev_id: null, next_id: '41'}, // next item - 41
  {id: '41', prev_id: '14', next_id: '22'}, // next item - 22
  {id: '22', prev_id: '41', next_id: '45'}, // next item - 45
  {id: '45', prev_id: '22', next_id: null},
]

I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id.

P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself


Solution

  • Create an index of items by id, find the 1st item (prev_id === null), and then iterate with a while loop, and push the current object into the result array:

    const findStart = R.find(R.propEq('prev_id', null))
    const indexById = R.indexBy(R.prop('id'))
    
    const sortByNextId = arr => {
      const index = indexById(arr)
      let current = findStart(arr)
      
      const sorted = []
      
      while(current) {
        sorted.push(current)
        current = index[current.next_id]
      }
      
      return sorted
    }
    
    const dll = [
      {id: '22', prev_id: '41', next_id: '45'},
      {id: '45', prev_id: '22', next_id: null},
      {id: '41', prev_id: '14', next_id: '22'},
      {id: '14', prev_id: null, next_id: '41'},
    ]
    
    const result = sortByNextId(dll)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>