Skip to content

Instantly share code, notes, and snippets.

@necojackarc
Last active September 25, 2019 16:29
Show Gist options
  • Save necojackarc/311900feae775592468ae90d7cd3c74d to your computer and use it in GitHub Desktop.
Save necojackarc/311900feae775592468ae90d7cd3c74d to your computer and use it in GitHub Desktop.
Format URL function that can be partially applied made for fun!
'use strict';
const qs = require('qs');
function format_url(base) {
const remove_trailing_slash = (element) => {
return element.endsWith('/') ? element.slice(1, -1) : element;
};
const remove_leading_slash = (element) => {
return element.startsWith('/') ? element.slice(1) : element;
};
const append_element = (current_base) => {
return (element) => {
if (!element) {
return current_base;
}
if (typeof(element) === 'object') {
return current_base + '?' + qs.stringify(element);
}
return append_element(remove_trailing_slash(current_base) + '/' + remove_leading_slash(element));
};
};
return append_element(base);
}
const base_url = format_url('https://example.com');
base_url('users')({ 'type': 'admin' }); // => https://example.com/users?type=admin
base_url('users')('1')('posts')(); // => https://example.com/users/1/posts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment