Skip to content

Instantly share code, notes, and snippets.

@shripadk
Created September 11, 2012 18:28
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 shripadk/3700599 to your computer and use it in GitHub Desktop.
Save shripadk/3700599 to your computer and use it in GitHub Desktop.
fix
var Route = function(pattern, callback) {
this.pattern = pattern;
this.callback = callback;
};
Route.prototype.matches = function(url) {
var params = {};
if(!url.length) return false;
if(url[url.length-1] === "/") {
url = url.slice(0, url.length-1);
}
var i=0, j=0;
for(i=0, j=0; i<url.length && j<this.pattern.length;) {
if(this.pattern[j] == '*') return true;
if(url[i] == this.pattern[j]) {
i++;
j++;
} else if(this.pattern[j] == ':') {
j++;
var name = this.skipPathNode(this.pattern, j);
var match = this.skipPathNode(url, i);
params[name] = match;
return params;
} else return false;
}
};
Route.prototype.skipPathNode = function(str, idx) {
var start = idx;
while(idx < str.length && str[idx] != '/') idx++;
return str.slice(start, idx);
};
/**
* Example 1:
* var route = new Route("/css/:file", function() { console.log("hit"); });
* if(route.matches("/css/awesome.css")) { route.callback() }
*
* Example 2:
* var route = new Route("/public/images/*", function() { console.log("hit"); });
* if(route.matches("/public/images/awesomeness/awesome.png")) { route.callback() }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment