X Tutup
The Wayback Machine - https://web.archive.org/web/20201028100826/https://github.com/feathersjs/feathers/issues/2102
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

Enhancement proposal: Full support for MongoDB-like sorting criteria in sorter #2102

Open
mhillerstrom opened this issue Oct 21, 2020 · 0 comments

Comments

@mhillerstrom
Copy link

@mhillerstrom mhillerstrom commented Oct 21, 2020

I propose that sorter should be non-destructively and fully backwards compatibly enhanced to support the MongoDB sorting criteria of sub objects e.g. sorter({name: 1, age: -1, "family.children.age": 1}). This will make the sorter very useful to use as part of many applications and can eliminate many ad hoc sorting code blocks for in-memory sorts.

It can be implemented like this (without any optimization):

exports function sorter ($sort: any) {
  function getVal (a: any, sortKeys: any) {
    let keys = sortKeys.map(key => key);
    let val = a;
    do {
      let key = keys.shift();
      val = val[key];
    } while (keys.length);

    return val;
  };

  const criteria = Object.keys($sort).map(key => {
    const direction = $sort[key];
    const keys = key.split('.');

    return { keys, direction };
  });

  return function (a: any, b: any) {
    let compare;

    for (const criterion of criteria) {
      compare = criterion.direction * exports.compare(getVal(a, criterion.keys), getVal(b, criterion.keys));

      if (compare !== 0) {
        return compare;
      }
    }

    return 0;
  };
}

Implemented like above, it will be backwards compatible (but a little bit slower - I think is is easy to optimize it but the prize to pay will be readability).

Of cause, if the proposal is implemented, it will be necessary to document it.

@daffl daffl transferred this issue from feathersjs/databases Oct 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.
X Tutup