techfort / LokiJS

javascript embeddable / in-memory database
http:/techfort.github.io/LokiJS
MIT License
6.71k stars 478 forks source link

simple sorting strings that kinda look like numbers but are not #900

Closed robguthrie closed 2 years ago

robguthrie commented 2 years ago

Hi, we've been using LokiJS for years in Loomio and I just cannot (love it | thank you) enough. I really would not want to have to use anything else for this job.

I wanted to ask about simplesort(). We use it to sort strings, which are composed in the format such as '001-001'

Here's a testcase to explain:

image

In short Loki is detecting that these are numbers in string format, and sorting as if they were integers. I wish to have Loki sort these as if they were strings.

I have seen some of the discussion about this decision in issues in here.

Currently I'm using the following code to override the comparison methods:

import loki from 'lokijs'

var cmp = function(a, b) {
  if (a == b) return 0;
  if (a < b) return -1;
  return 1;
}

// attach aeq onto loki.Comparators
loki.Comparators.aeq = function(a, b) {
  return cmp(a, b) === 0;
}

// attach lt onto loki.Comparators
loki.Comparators.lt = function(a, b, eq) {
    var result = cmp(a, b);
    switch(result) {
      case -1: return true;
      case 0: return eq;
      case 1: return false;
    }
}

// attach gt onto loki.Comparators
loki.Comparators.gt = function(a, b, eq) {
  var result = cmp(a, b);
    switch(result) {
      case -1: return false;
      case 0: return eq;
      case 1: return true;
    }
}

export default loki

Is there a better way to approach this. The code make me anxious because I'm not sure I can trust it in all cases. In particular I'm not sure if this relates to find() methods as well as sorting. I tend to use $jgt and $jlt to ensure that I'm getting simple javascript comparison with the find method, which I think is working well.

Is there a better way for me to get the sorting result I want?

Thank you!

robguthrie commented 2 years ago

So, I've been reading up and found simplesort('name', { useJavascriptSorting: true }) but it gives the same result.

I'm actually happy with the comparison function overload I have, so, just reply if you happen to have any ideas about what I should be doing better... but otherwise things are fine.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.