Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Entities: Add a sort key or function at store creation #491

Open
eversnarf opened this issue Oct 4, 2023 · 0 comments
Open

Entities: Add a sort key or function at store creation #491

eversnarf opened this issue Oct 4, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@eversnarf
Copy link
Sponsor

eversnarf commented Oct 4, 2023

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

@NetanelBasal NetanelBasal added the enhancement New feature or request label Nov 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants