DEV Community

Zee
Zee

Posted on

Is there a drop in JS Array-compatible React/Vue-friendly linked-list library?

Hello friends!

I have the following collection:

messages = [{ ... }, { ... } ]

Which I sometimes map over, unshift, and push onto. It hit me... 2 months ago... that really it needs to be a linked list, and not an array; as sometimes I need to render different things depending on information in the next or previous message.

I've procrastinated swapping out the collection's underlying data structure because most of the bugs were not related to the array-ness of the messages collection.

However I'm finally butting up against some bugs (again) where swapping the array for a linked list seems like the most reasonable course of action.

Do any of you know about a drop-in JavaScript Array replacement that plays nicely with the reactive nature of Vue 2?

I've found that most drop-in replacements don't take into account that Vue requres you to use Vue.set when adding new properties to an Object; and most LinkedList implementations use an object as their underlying data structure.

Any help would be greatly appreciated!

Zee

Top comments (1)

Collapse
 
zspencer profile image
Zee • Edited

Hey everyone!

Here's what I wound up doing:

All my calls to push and pop into this array were encapsulated in calls to prependMessage and appendMessage; so I wrote a quick function to link the items within the array to their previous or next item on push or unshift :

export function relinkMessageAtIndex(messages, index) {
  const foundItem = messages[index];
  const nextItem = messages[index + 1];
  const previousItem = messages[index - 1];
  Vue.set(foundItem, "previousMessage", previousItem);
  Vue.set(foundItem, "nextMessage", nextItem);
  if (nextItem) {
    Vue.set(nextItem, "previousMessage", foundItem);
  }
  if (previousItem) {
    Vue.set(previousItem, "nextMessage", foundItem);
  }
}

It's maybe not as 'right' as a real linked list, which encapsulates this transparently but it's "good enough" in the sense that it works and didn't require too much open heart surgery, and saved me a hundred lines.