Skip to content

Instantly share code, notes, and snippets.

@jdelight
Last active September 8, 2015 13:09
Show Gist options
  • Save jdelight/0f2fb3ceb3234703b099 to your computer and use it in GitHub Desktop.
Save jdelight/0f2fb3ceb3234703b099 to your computer and use it in GitHub Desktop.
Construct a URL path, replacing ":placeholder" with values
define([
'src/urls'
], function(
urls
) {
'use strict';
var slice = Array.prototype.slice;
return function url(name) {
if (!(name in urls)) {
throw name + " is not a valid url";
}
var route = '/' + urls[name][0],
params = slice.call(arguments, 1),
lastArg = params[params.length - 1],
queryString = "";
if (typeof lastArg === "object") {
queryString = "?" + $.param(lastArg);
params = params.slice(0, params.length - 1);
}
return params.reduce(function(fragment, param) {
return fragment.replace(/:[^/]+/.exec(fragment)[0], param);
}, route) + queryString;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment