diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/lib/url.js | 25 | ||||
-rw-r--r-- | src/lib/url.test.js | 20 |
2 files changed, 45 insertions, 0 deletions
diff --git a/src/lib/url.js b/src/lib/url.js new file mode 100644 index 0000000..b3ef40c --- /dev/null +++ b/src/lib/url.js @@ -0,0 +1,25 @@ +import { location, history } from 'browser-monads' +export const parseQuery = ({ search } = location) => + search && parseQueryString(search) + +const parseQueryString = query => + query + .split('?')[1] + .split('&') + .reduce((acc, pair) => { + const [key, val] = pair.split('=') + return { + ...acc, + [key]: val + } + }, {}) + +export const objectToQuery = query => + Object.entries(query).reduce( + (acc, [key, val], i) => acc + `${i !== 0 ? '&' : ''}${key}=${val}`, + '?' + ) + +export const writeQuery = (queryObj, { pushState } = history) => { + pushState({}, '', objectToQuery(queryObj)) +} diff --git a/src/lib/url.test.js b/src/lib/url.test.js new file mode 100644 index 0000000..76137b8 --- /dev/null +++ b/src/lib/url.test.js @@ -0,0 +1,20 @@ +import { parseQuery as parseQueryGlobal, objectToQuery } from './url' + +const parseQuery = search => + parseQueryGlobal({ + search + }) + +test('parseQuery', () => { + expect(parseQuery('?mySearch=myVal')).toEqual({ mySearch: 'myVal' }) + expect(parseQuery('?mySearch=myVal&againWith=aVal')).toEqual({ + mySearch: 'myVal', + againWith: 'aVal' + }) + // test that these 2 functions are inverses + // (e.g composing them produces `const f = k => k`) + let input = '?big=long&one=eh' + expect(objectToQuery(parseQuery(input))).toEqual(input) + input = { args: 'hi', onArgs: 'helloagain' } + expect(parseQuery(objectToQuery(input))).toEqual(input) +}) |