-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuris.js
More file actions
43 lines (36 loc) · 1009 Bytes
/
uris.js
File metadata and controls
43 lines (36 loc) · 1009 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//uri-friendly json notation
const flipObj = obj =>
Object.keys(obj).reduce ((acc, key) =>
(acc[obj[key]] = key) && acc
, {})
const uriMap = (to => ({
to, from: flipObj (to)
})) ({',"':'&', '":':'=', '"':"~"})
export const toUri = obj =>
'#' + encodeURI (
replaceInString (
JSON.stringify(obj)
.slice(2, -1),
uriMap.to
)
)
export const fromUri = uriString =>
uriString.length <= 1 ? {} :
JSON.parse ( '{"' + replaceInString (decodeURI(
addTerminator ('~') (convertLegacy (uriString)).slice(1)
), uriMap.from) + '}')
const addTerminator = term => uriString =>
(uriString.split (term)).length % 2 ?
uriString : uriString + term
const convertLegacy = string =>
string.includes (':') ?
console.warn ('you are using the legacy URI format, please switch') ||
replaceInString (string, {
':':'=', "'": '~', ',':'&'
})
: string
const replaceInString = (string, replaceMap) =>
Object.entries(replaceMap).reduce (
(acc, val) => acc.split(val[0]).join(val[1]),
string
)