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

Natural sort #116

Open
freefly42 opened this issue Apr 27, 2023 · 1 comment
Open

Natural sort #116

freefly42 opened this issue Apr 27, 2023 · 1 comment

Comments

@freefly42
Copy link

I use this for giving access to build distributions hosted in private S3 buckets, and find that alphanumeric sorting results in confusion over what the "latest" build is. So I added a natural sort function that I call on the directories and the folders so that "99.txt" will appear before "100.txt". Actually, in my implementation I now reverse sort the numbers so that the highest build number will always be at the top of the list, but the text portions are sorted alphabetically:

function naturalSort(a, b) {
  // Extract strings and numbers from filenames
  var regex = /(\D+)|(\d+)/g;
  var aParts = a.Key.match(regex);
  var bParts = b.Key.match(regex);

  // Compare corresponding parts of the filenames
  while (aParts && bParts && aParts.length > 0 && bParts.length > 0) {
    var aPart = aParts.shift();
    var bPart = bParts.shift();
    if (aPart !== bPart) {
      var aNum = parseInt(aPart, 10);
      var bNum = parseInt(bPart, 10);
      if (isNaN(aNum) || isNaN(bNum)) {
        // Sort by string part
        return aPart.localeCompare(bPart);
      } else {
        // Sort by numerical part
        if (aNum !== bNum) {
          return bNum - aNum;
        }
      }
    }
  }

  // If filenames have different numbers of parts, sort by length
  return aParts.length - bParts.length;
}

It works by splitting the names by "decimal" vs "not-decimal" segments, and if a corresponding segment of both names is numeric it Performas a numerical sorting, if either is non-numeric than alphabetical sorting is used. The result is that natural number sorting will occur regardless of where in the file/directory name the number appears. Since this is done in the browser I don't care much that it's less efficient than other sorting mechanisms, it produces highly desirable results.

@rufuspollock
Copy link
Owner

@freefly42 thanks for sharing. Are you suggesting this going into core? that would be welcome though we'd need a PR 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants