summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNick Van Doorn <vandoorn.nick@gmail.com>2019-04-05 15:30:19 -0700
committerNick Van Doorn <vandoorn.nick@gmail.com>2019-04-05 15:30:22 -0700
commitaef00b7ede3167290ef64feacc7e795463428547 (patch)
tree2ff56c69b3560273a0afdbb54daa5a26ed635697
parentdb98f83ed0e0ff2fc0f68b46446d32ac81cd253f (diff)
Roll small URL lib
-rw-r--r--src/lib/url.js25
-rw-r--r--src/lib/url.test.js20
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)
+})