Skip to content

Instantly share code, notes, and snippets.

@maranomynet
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maranomynet/b3070a9aa08219566508 to your computer and use it in GitHub Desktop.
Save maranomynet/b3070a9aa08219566508 to your computer and use it in GitHub Desktop.
Sorting mithril-style routes logically
// https://gist.github.com/maranomynet/b3070a9aa08219566508
var _sortRoutes = function ( routes ) {
var sortedRoutes = {};
var tokens = {};
var tokenize = function (str) {
var token = tokens[str];
if ( token == null )
{
token = tokens[str] = str
// Sort order: ? < n < s < v < …
.replace(/\.{3}/g,'…') // mark variadics (`...`)
.replace(/\?.+$/, '?') // queryStrings
.replace(/[^\/:…\?]+/gi, 'n') // folder-names
.replace(/\//g, 's') // slashes
.replace(/:n/g, 'v') // :variables
.replace(/v…/g, '…'); // sort :variadics... last
}
return token;
};
Object.keys(routes)
.sort( function ( a, b ) {
a = tokenize(a);
b = tokenize(b);
return a>b ? 1 : a<b ? -1 : 0;
})
.forEach( function (route) { sortedRoutes[route] = routes[route]; } );
return sortedRoutes;
};

Usage:

m.route( document.body, '/', _sortRoutes( myRoutesObject ) );

This would qualify as a fully sorted route-list:

  1. relative/path (<-- makes little sense, but hey)
  2. /
  3. /static
  4. /static/static
  5. /static/static?silly=query
  6. /static/static/static
  7. /static/:variable
  8. /static/:variable/:variable2
  9. /static/:gobble...
  10. /:variable/static
  11. /:variable/static/
  12. /:gobble...
  13. :gobble...
@maranomynet
Copy link
Author

So where should the route /static:variable (note the lack of "/" delimeter) land in the sorted list above?

Should we even care?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment