Created
June 15, 2017 16:48
-
-
Save jonathan-fulton/167dc8833b9058eafc5cdebc3a2609a9 to your computer and use it in GitHub Desktop.
build-url: the good way
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
function buildUrl(url, options) { | |
const baseUrl = _getBaseUrl(url); | |
const opts = _getOptions(url, options); | |
if (!opts) { | |
return baseUrl; | |
} | |
urlWithPath = _appendPath(baseUrl, opts.path); | |
urlWithPathAndQueryParams = _appendQueryParams(urlWithPath, opts.queryParams) | |
urlWithPathQueryParamsAndHash = _appendHash(urlWithPathAndQueryParams, opts.hash); | |
return urlWithPathQueryParamsAndHash; | |
}; | |
function _getBaseUrl(url) { | |
if (url === null || typeof(url) === 'object') { | |
return ''; | |
} | |
return url; | |
} | |
function _getOptions(url, options) { | |
if (typeof(url) === 'object') { | |
return url; | |
} | |
return options; | |
} | |
function _appendPath(baseUrl, path) { | |
if (!path) { | |
return baseUrl; | |
} | |
return baseUrl += '/' + path; | |
} | |
function _appendQueryParams(urlWithPath, queryParams) { | |
if (!queryParams) { | |
return urlWithPath | |
} | |
const keyValueStrings = Object.keys(queryParams).map(key => { | |
return `${key}=${queryParams[key]}`; | |
}); | |
const joinedKeyValueStrings = keyValueStrings.join('&'); | |
return `${urlWithPath}?${joinedKeyValueStrings}`; | |
} | |
function _appendHash(urlWithPathAndQueryParams, hash) { | |
if (!hash) { | |
return urlWithPathAndQueryParams; | |
} | |
return `${urlWithPathAndQueryParams}#${hash}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactored version of main file from build-url module: https://github.com/steverydz/build-url/blob/master/src/build-url.js