1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
function lookupCookieValue(name) { |
18 |
var tupleString = detect(split(asString(document.cookie), '; '), function(tuple) { |
19 |
return startsWith(tuple, name); |
20 |
}, function() { |
21 |
throw 'Cannot find value for cookie: ' + name; |
22 |
}); |
23 |
|
24 |
return decodeURIComponent(contains(tupleString, '=') ? split(tupleString, '=')[1] : ''); |
25 |
} |
26 |
|
27 |
function lookupCookie(name, failThunk) { |
28 |
try { |
29 |
return Cookie(name, lookupCookieValue(name)); |
30 |
} catch (e) { |
31 |
if (failThunk) { |
32 |
return failThunk(); |
33 |
} else { |
34 |
throw e; |
35 |
} |
36 |
} |
37 |
} |
38 |
|
39 |
function existsCookie(name) { |
40 |
var exists = true; |
41 |
lookupCookie(name, function() { |
42 |
exists = false; |
43 |
}); |
44 |
return exists; |
45 |
} |
46 |
|
47 |
var update = operator(); |
48 |
var remove = operator(); |
49 |
function Cookie(name, val, path) { |
50 |
val = val || ''; |
51 |
path = path || '/'; |
52 |
document.cookie = name + '=' + val + '; path=' + path; |
53 |
|
54 |
return object(function(method) { |
55 |
method(value, function(self) { |
56 |
return lookupCookieValue(name); |
57 |
}); |
58 |
|
59 |
method(update, function(self, val) { |
60 |
document.cookie = name + '=' + encodeURIComponent(val) + '; path=' + path; |
61 |
return self; |
62 |
}); |
63 |
|
64 |
method(remove, function(self) { |
65 |
var date = new Date(); |
66 |
date.setTime(date.getTime() - 24 * 60 * 60 * 1000); |
67 |
document.cookie = name + '=; expires=' + date.toGMTString() + '; path=' + path; |
68 |
}); |
69 |
|
70 |
method(asString, function(self) { |
71 |
return 'Cookie[' + name + ', ' + value(self) + ', ' + path + ']'; |
72 |
}); |
73 |
}); |
74 |
} |