Last active
August 29, 2015 13:57
-
-
Save simenbrekken/9369290 to your computer and use it in GitHub Desktop.
Simple RegExp-based Router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "Routes" | |
function Home() { | |
console.log('Home') | |
} | |
function Products(params) { | |
console.log(params.category, 'products') | |
} | |
function ProductDetails(params) { | |
console.log('Product #' + params.id) | |
} | |
function NotFound() { | |
console.log('Not found :(') | |
} | |
var router = new Router() | |
router.add('/', Home) | |
router.add(/^\/products\/([0-9]+)$/, ProductDetails, 'id') | |
router.add('/products/:category', Products) | |
router.add('*', NotFound) | |
console.log(router.match('/')) | |
console.log(router.match('/products/sports')) | |
console.log(router.match('/products/123')) | |
console.log(router.match('/nope')) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function Router(routes) { | |
this.routes = routes || [] | |
} | |
Router.prototype.add = function(pattern, handler) { | |
var route = { | |
names: [], | |
handler: handler | |
} | |
if (pattern instanceof RegExp) { | |
route.pattern = pattern | |
route.names = Array.prototype.slice.call(arguments, 2) | |
} else if (typeof pattern == 'string') { | |
route.pattern = new RegExp('^' + pattern.replace(/\*/g, '(.*)').replace(/(?::([^\/]+))/g, function(match, name) { | |
route.names.push(name) | |
return '([^\/]+)' | |
}) + '$') | |
} else { | |
route = pattern | |
} | |
this.routes.push(route) | |
return route | |
} | |
Router.prototype.match = function(url) { | |
for (var i = 0, l = this.routes.length; i < l; i++) { | |
var route = this.routes[i] | |
var matches = route.pattern.exec(url) | |
if (matches) { | |
var names = route.names, | |
params = {} | |
for (var j = 0, k = names.length; j < k; j++) { | |
params[names[j]] = matches[j + 1] | |
} | |
return { | |
params: params, | |
handler: route.handler | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment