Skip to content

Instantly share code, notes, and snippets.

@park-brian
Last active May 8, 2020 20:37
Show Gist options
  • Save park-brian/01caabb7f9ab380a01c208eba8c70823 to your computer and use it in GitHub Desktop.
Save park-brian/01caabb7f9ab380a01c208eba8c70823 to your computer and use it in GitHub Desktop.
Regex Router
/*
Routing consists of matching a string against a set of regular expressions to call a function.
In this case, we can define routes as an array of regular expressions and callbacks.
For example:
let routes = [
[/^\/user\/(\d+)\/?$/, (id) => response({id})],
[/^\/user\/([a-z0-9-_]+)\/?$/, (name) => response({name})],
[/^\/user\/([a-z0-9-_]+)\/(\d+)\/?$/, (name, id) => response({id, name})],
];
If needed, we can provide our own procedures for converting user-supplied routes into regular expressions.
We can also provide some post-processing to convert regex results to the proper types by wrapping each callback in a decorator
*/
const router = routes => route => {
for (let i = 0; i < routes.length; i ++) {
let [regex, callback] = routes[i];
let match = route.match(regex);
if (match) {
return callback.apply(null, match.slice(1));
};
}
}
// usage: let r = router(routes); r('/user/john/100');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment