ngneat/elf

Entities: Add a sort key or function at store creation

eversnarf opened this issue · 0 comments

Which @ngneat/elf-* package(s) are relevant/releated to the feature request?

entities

Description

I want to store various entities in my store and keep them ordered by a given key, or even better a comparator function, so that subscribers can receive the collection in the expected order, even if I do multiple removals and insertions.
However, entities are kept in the same sequence as their insertion order (except if one uses the prepend option), and thus served in the same order to subscribers.

Proposed solution

Sort key

const todosStore = createStore(
  { name: 'todos' },
  withEntities<Todo, '_index'>({ sortKey: '_index' })
);

Sort function

const todosStore = createStore(
  { name: 'todos' },
  withEntities<Todo>({ sortFn: (a, b) => {a._index - b._index}  })
);

Alternatives considered

Sort at subscriber level

Of course, I can do the sorting at each subscriber level, but this means:

  • each subscriber has to know about the sorting logic
  • we need to sort for every mutation, even if it does not affect the order of the entities

Sort and update all entities

        emitOnce(() => {
            const entities: CoatEdit[] = store.query(getAllEntities());
            entities.sort(sortFn);
            store.update(deleteAllEntities(), addEntities(entities));
        });

moveEntity

This implies moving entities one-by-one, and feels cumbersome.

Do you want to create a pull request?

No