Search code examples
typescriptdictionaryordereddictionary

Typescript Ordered Dictionary


I need to store relatively big amount of data sorted with index, something similar to editable chat - ordered by time and with random access for editing.

The number of items are relatively big and the number of "index" operation is similar to the number of "sort" actions. I don't prevent the calculation of the "search" or the "sort" each time and I search for smarter collection.

I tried to find Ordered Dictionary collection, but I just saw solutions that use regular dictinary and calculate Object.values(dict).sort() which is too expansive, I believe, if dict is big and you need to sort if every ~1sec.

TL;DR
Is there Ordered Dictionary collection or something similar in TypeScript?


Solution

  • I think what you're looking for is Map. A Map is guaranteed to keep the order of insertion while you're iterating it.

    Objects might work for you too. Since ES2015, the iteration order is not exactly insert-order, but it is predictable.

    I prefer to use Maps over Objects when the keys come from user input or when they aren't properties of a known shape. It's similar to Dictionaries vs. Records in other languages you might be familiar with.