Created
December 22, 2017 03:11
-
-
Save benmccormick/a5c99d5a2cd404d7bd4618c17a0dd64c to your computer and use it in GitHub Desktop.
Params fn
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
/* 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('&')}` : ''; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mergeTagSafeEncode
is a domain specific function in my use, but for general use you could replace it withencodeURIComponent