-
Notifications
You must be signed in to change notification settings - Fork 80
/
cookie.js
72 lines (58 loc) · 1.67 KB
/
cookie.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
function tryParse (obj) {
try {
return JSON.parse(obj)
} catch (e) {}
return obj
}
function tryStringify (obj) {
if (typeof obj !== 'object' || !JSON.stringify) return obj
return JSON.stringify(obj)
}
var cookie = {}
cookie.set = function (name, value, expires, path, domain) {
var pair = escape(name) + '=' + escape(tryStringify(value))
var expiresTruthy = !!expires
if (expiresTruthy) {
if (expires.constructor === Number) pair += ';max-age=' + expires
else if (expires.constructor === String) pair += ';expires=' + expires
else if (expires.constructor === Date) pair += ';expires=' + expires.toUTCString()
}
var pathTruthy = !!path
pair += ';path=' + ((pathTruthy) ? path : '/')
var domainTruthy = !!domain
if (domainTruthy) pair += ';domain=' + domain
document.cookie = pair
return cookie
}
cookie.setObject = function (object, expires, path, domain) {
for (var key in object) cookie.set(key, object[key], expires, path, domain)
return cookie
}
cookie.get = function (name) {
var obj = cookie.getObject()
return obj[name]
}
cookie.getObject = function () {
var pairs = document.cookie.split(/;\s?/i)
var object = {}
var pair
for (var i in pairs) {
if (typeof pairs[i] === 'string') {
pair = pairs[i].split('=')
if (pair.length <= 1) continue
object[unescape(pair[0])] = tryParse(unescape(pair[1]))
}
}
return object
}
cookie.unset = function (name) {
var date = new Date(0)
document.cookie = name + '=; expires=' + date.toUTCString()
return cookie
}
cookie.clear = function () {
var obj = cookie.getObject()
for (var key in obj) cookie.unset(key)
return obj
}
module.exports = cookie