Skip to content

Instantly share code, notes, and snippets.

@necojackarc
Last active Sep 25, 2019
Embed
What would you like to do?
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