Skip to content

Instantly share code, notes, and snippets.

@benmccormick
Created December 22, 2017 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benmccormick/a5c99d5a2cd404d7bd4618c17a0dd64c to your computer and use it in GitHub Desktop.
Save benmccormick/a5c99d5a2cd404d7bd4618c17a0dd64c to your computer and use it in GitHub Desktop.
Params fn
/* takes a list of params in the format
[{
key: 'foo'
value: 'bar'
}]
or an object with key-value params
{
foo: 'bar'
}
}
*/
export const paramString = (params = [], encode = false) => {
let encodeFn = encode ? mergeTagSafeEncode : _.identity;
let buildPair = (value, key) => `${encodeFn(key)}=${encodeFn(value)}`;
if (_.isArray(params)) {
params = _(params)
.filter(_.isObject)
.map(
({ key, value }) => (key && value ? buildPair(value, key) : '')
)
.value();
} else {
params = _.map(params, buildPair);
}
return params.length ? `?${params.join('&')}` : '';
};
@benmccormick
Copy link
Author

mergeTagSafeEncode is a domain specific function in my use, but for general use you could replace it with encodeURIComponent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment