URL Pattern Parser
// We need to write a function in JavaScript that parses all the variable parts of a
// url, and any url parameters, into a hash. The function should take two arguments:
// 1. A "url format" string, which describes the format of a url that can contain
// constant parts and variable parts (where "parts" of a url are separated with "/").
// All variable parts begin with a colon. Here is an example "url format" string:
// "/v6/:collecton/:id"
// 2. The second argument is a particular url that is guaranteed to have the format
// specified by the first argument. It may also contain url parameters. For instance,
// given the example url format string above, the second argument might be:
// "/v6/photos/3?size=large&res=high
// Given these two arguments, our parsing function should return a hash that maps
// the variable parts of the url and any supplied url parameters to their values:
// {
// collection: "photos",
// id: "3",
// size: "large",
// res: "high"
// }
// Please write the parsing function.
function urlParse(urlFormat, url) {
var result = {},
urlMask = [],
maskIndex = 0,
urlFormatSplit,
queryString,
param, value, i;
// seperate things as necessary
urlFormatSplit = urlFormat.split("/");
queryString = url.split("?")[1];
urlPart = url.split("?")[0];
urlSplit = urlPart.split("/");
// determine which indices represent variables
for (i = 0; i < urlFormatSplit.length; i++) {
debugger;
if (urlFormatSplit[i].indexOf(':') === 0) {
var name = urlFormatSplit[i].substr(1, this.length);
urlMask.push({ "index" : i, "name" : name });
}
}
// [{ "index" : 1, "name" : "collection" },
// { "index" : 2, "name" : "id" }]
for (i = 0; i < urlSplit.length; i++) {
if (urlMask[maskIndex].index === i) {
var key = urlMask[maskIndex].name;
result[key] = urlSplit[i];
maskIndex += 1;
}
}
// pull out qs values and add to result
queryStringSplit = queryString.split("&");
for (i = 0; i < queryStringSplit.length; i++) {
var thisParamAndResult = queryStringSplit[i].split("=");
var key = thisParamAndResult[0];
result[key] = thisParamAndResult[1];
}
return result;
}
(function() {
var urlFormat = "/v6/:collecton/:id";
var url = "/v6/photos/3?size=large&res=high";
var result = urlParse(urlFormat, url);
console.log("result:");
console.log(result);
})();