Multi-Index: Containers with more than one index
Multi-index separates container storage from indexing. You store a set of objects and access them using any key you can compute from those objects.
Containers
Create a container:
; ;
Everything works if you're using JavaScript, you'll just not bother with types:
const Container uniqueIndex nonuniqueIndex = ; const c = ;
Usually you'd add some indexes, but you can already add objects to that container:
;c.addjoeBloggs .add .add;
You can also delete, but it has to be the same object you added:
c.deletejoeBloggs;
But let's keep Mr. Bloggs in there so we can look at indices...
c.addjoeBloggs;
Indices
Add a few indices:
;;
Or in JavaScript, just don't add types to the functions:
const byId = ;const byNickname = ;
Unique indices won't let you add the same element twice:
c.add; // throws NonuniqueIndexError
(They also test for uniqueness if you add them to a container with
existing indexes, so byNickname
above could not be unique.)
Now you can look up elements:
byId.get23; // returns { id: 23, name: 'Joseph', nickname: 'joe' }byNickname.get'joe'; // returns Set([{ id: 23, name: 'Joseph', nickname: 'joe' }, joeBloggs])
Related projects
- indexify: A similar lightweight package, supports containers with multiple indexes. API is not type-safe for TypeScript. Less extensible.
- bimap: A specific container with 2 indices. You could implement a bidirectional map using a multi-index container.
- bim: Another bidirectional map.
- mnemonist: A variety of lower-level data structures. Unfortunately does not include multi-indexed containers.
- Boost multi_index: the ultimate multi-indexed container, for C++; highly performant.