Created
September 11, 2012 18:28
-
-
Save shripadk/3700599 to your computer and use it in GitHub Desktop.
fix
This file contains hidden or 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
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