Skip to content

Instantly share code, notes, and snippets.

@dseg
Created February 23, 2017 08:59
Show Gist options
  • Save dseg/4f42bceaaf23885d90d108cf992e9d1f to your computer and use it in GitHub Desktop.
Save dseg/4f42bceaaf23885d90d108cf992e9d1f to your computer and use it in GitHub Desktop.
Crafting a query string from an array using ES6's template literal feature
/**
* Template String Tag (For crafting query-string for HTTP/Get from a array)
*
* Usage: qsTag`${['a','b','c','d']}`(); // a=b&c=d
*/
export const qsTag = (strings, ...keys) => (...values) => {
let result = [];
const input = keys[0];
input.forEach((key: any, i: number, ary: any[]) => {
const postfix = (ary.length-1 === i ? '' : '&');
if (i > 0 && i % 2 === 1) {
result.push(`${input[i-1]}=${input[i]}${postfix}`);
}
});
return result.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment