Created
February 26, 2019 14:23
-
-
Save saxena-gaurav/3ad7622d7e6b4529018190dadb2e6b88 to your computer and use it in GitHub Desktop.
Object Route Mapper
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 a = { | |
"/test": "Route1", | |
"/test/:testId": "Route2", | |
"/test/:testId/test1/:testId1": "Route3" | |
} | |
var route = function(a, path) { | |
var res = {}; | |
res.params = {}; | |
var k, p; | |
var keys = Object.keys(a); | |
for (var j = 0; j < keys.length; j++) { | |
if (keys[j] === path) { | |
res.ctrl = a[keys[j]]; | |
break; | |
} else { | |
k = keys[j].split("/"); | |
p = path.split("/"); | |
if (k.length == p.length) { | |
for (var i = 0; i < k.length; i++) { | |
if (k[i].startsWith(":")) { | |
res.params[k[i].substring(1)] = p[i]; | |
} | |
} | |
res.ctrl = a[keys[j]]; | |
} | |
} | |
} | |
console.log(res); | |
} | |
route(a, '/test') //{ "ctrl": Route1, "params":{}} | |
route(a, '/test/1') //{ "ctrl": Route2, "params":{testId: 1}} | |
route(a, '/test/1/test1/2') //{ "ctrl": Route3, "params":{testId: 1, testId1: 2}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment