Skip to content

Instantly share code, notes, and snippets.

@xedef
Last active September 5, 2016 03:21
Show Gist options
  • Save xedef/c16245627a76a90f3b30666f853c7f29 to your computer and use it in GitHub Desktop.
Save xedef/c16245627a76a90f3b30666f853c7f29 to your computer and use it in GitHub Desktop.
Intelligently buils an URL from the arguments.
/**
* NOTE: Requires Underscore >=1.4.3
*
* Intelligently buils an URL from the arguments.
* . If the parameter is a string or a number, is part or the URL (in the order passed)
* . If the parameter is an object, is taken as a query param.
*
* Examples:
* urlBuilder('http://google.com')
* 'http://google.com'
*
* urlBuilder('http://myrestapi.com', 'users')
* 'http://myrestapi.com/users'
*
* urlBuilder('http://myrestapi.com', 'user', userId, 'posts')
* 'http://myrestapi.com/user/{userId}/posts'
*
* urlBuilder('http://myrestapi.com', 'user', userId, 'posts', {page: 2, limit:10})
* 'http://myrestapi.com/user/{userId}/posts?page=2&limit=10'
*
* @return {string} The formed URL.
*/
function urlBuilder() {
var argsArr = Array.prototype.slice.call(arguments);
var args = _.groupBy(argsArr, function(arg) {
if (_.isString(arg) || _.isNumber(arg)) {
return 'paths';
}
if (_.isObject(arg)) {
return 'params';
}
});
// error: no path passed
if (_.size(args.paths) === 0) {
return '';
}
// replace double slashes without loosing '://'
var exp = new RegExp('([^:])//'),
url = args.paths.join('/').replace(exp, '$1/');
if (!_.isEmpty(args.params)) {
// build the query string
url += '?' + _.map(_.extend.apply(_, _.union([{}], args.params)), function(value, key) {
return key + '=' + value;
}).join('&');
}
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment