Created
February 23, 2017 08:59
-
-
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
This file contains 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
/** | |
* 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