Last active
March 23, 2017 12:05
-
-
Save kofno/626bf661fa1e69f3dadb799c980cfcf9 to your computer and use it in GitHub Desktop.
convert an object to a query string
This file contains hidden or 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
| import R from 'ramda'; | |
| const insertAmps = R.join('&'); | |
| const insertEquals = R.map(R.join('=')); | |
| const makeKeys = R.curry((f, pairs) => { | |
| const makeKeys_ = pair => [f(pair[0]), pair[1]]; | |
| return R.map(makeKeys_, pairs); | |
| }); | |
| const encodePairs = pairs => { | |
| const encodeAll = R.map(encodeURIComponent); | |
| return R.map(encodeAll, pairs); | |
| }; | |
| const isPresent = val => !R.isNil(val) && !R.isEmpty(val); | |
| const sndIsPresent = R.pipe(R.prop(1), isPresent); | |
| const filterPresentValues = R.map(sndIsPresent); | |
| const toQueryImpl = R.curry((f, obj) => { | |
| const fn = R.pipe( | |
| R.toPairs, | |
| filterPresentValues, | |
| encodePairs, | |
| makeKeys(f), | |
| insertEquals, | |
| insertAmps, | |
| ); | |
| return fn(f, obj); | |
| }); | |
| export const toQuery = toQueryImpl(R.identity); | |
| export const mapKeysToQuery = toQueryImpl; | |
| /* Example usage: | |
| * | |
| * const query = { param1: 'foo', param2: 'bar', param3: '' } | |
| * import { mapKeysToQuery } from 'query-params'; | |
| * mapKeysToQuery((k) => `asset_filter[${k}]`, query); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment