diff options
author | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-04-05 15:30:19 -0700 |
---|---|---|
committer | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-04-05 15:30:22 -0700 |
commit | aef00b7ede3167290ef64feacc7e795463428547 (patch) | |
tree | 2ff56c69b3560273a0afdbb54daa5a26ed635697 /src | |
parent | db98f83ed0e0ff2fc0f68b46446d32ac81cd253f (diff) |
Roll small URL lib
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) +}) |