Created
November 16, 2015 07:39
-
-
Save toruta39/2e761cb19cc75ec1d2e7 to your computer and use it in GitHub Desktop.
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
let rules = []; | |
function appendRule(path, callback) { | |
rules.push([path, callback]); | |
} | |
function matchPath(path, currentPath) { | |
let params = {}; | |
// If there's a '/' in the end of path, trim it. | |
currentPath = currentPath.replace(/\/$/, ''); | |
let pathRegExp = path.replace(/\/$/, '') | |
.replace(/\*/g, '.*') | |
.replace(/\/:([^?\/])+/g, '(/[^/]+)') | |
.replace(/\//g, '\\/'); | |
pathRegExp = new RegExp('^' + pathRegExp + '$'); | |
let paramNames = path.match(/:([^?\/])+/g); | |
if (paramNames) { | |
for (let i = 0, len = paramNames.length; i < len; i++) { | |
paramNames[i] = paramNames[i].substr(1); | |
} | |
} | |
let matches = pathRegExp.exec(currentPath); | |
if (matches === null) { | |
return false; | |
} else { | |
matches.shift(); | |
for (let i = 0, len = matches.length; i < len; i++) { | |
if (matches[i]) { | |
params[paramNames[i]] = matches[i].substr(1); | |
} | |
} | |
return params; | |
} | |
} | |
let validateIndex = 0; | |
function exec() { | |
validateIndex = 0; | |
validate(); | |
} | |
function validate() { | |
if (validateIndex < rules.length) { | |
let next = function() { | |
validateIndex++; | |
validate(); | |
}; | |
let params = matchPath(rules[validateIndex][0], location.pathname); | |
if (params) { | |
rules[validateIndex][1](params, next); | |
} else { | |
next(); | |
} | |
} | |
return; | |
} | |
let interphace = { | |
add: appendRule, | |
exec: exec | |
}; | |
export default interphace; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment