Modernize session script with minor fixes and additional tests
Change-Id: Ic76d591e982e4f6e17fbe0f57400a3ac9f5bfa14
diff --git a/dev/js/src/session.js b/dev/js/src/session.js
index 178b83c..92bbadf 100644
--- a/dev/js/src/session.js
+++ b/dev/js/src/session.js
@@ -4,19 +4,23 @@
*
* @author Nils Diewald
*/
+
+"use strict";
+
define({
/**
* Create a new session.
* Expects a name or defaults to 'korap'
*/
create : function (name = 'korap') {
- var obj = Object.create(this);
+ const obj = Object.create(this);
obj._name = name.toLowerCase();
obj._hash = {};
obj._parse();
return obj;
},
+
/**
* Get a value based on a key.
* The value can be complex, as the value is stored as JSON.
@@ -25,6 +29,7 @@
return this._hash[key.toLowerCase()];
},
+
/**
* Set a value based on a key.
* The value can be complex, as the value is stored as JSON.
@@ -34,37 +39,49 @@
this._store();
},
+
/**
* Clears the session by removing the cookie
*/
clear : function () {
+ this._hash = {};
document.cookie = this._name + '=; expires=-1';
},
+
/* Store cookie */
_store : function () {
+ document.cookie = this.toString();
+ },
+
+
+ /**
+ * Stringify session cookie.
+ */
+ toString : function () {
/*
var date = new Date();
date.setYear(date.getFullYear() + 1);
*/
- document.cookie =
- this._name + '=' + encodeURIComponent(JSON.stringify(this._hash)) + ';';
+ return this._name + '=' + encodeURIComponent(JSON.stringify(this._hash)) + ';';
},
- /* Parse cookie */
+
+ /**
+ * Parse cookie
+ */
_parse : function () {
- var c = document.cookie;
document.cookie.split(';').forEach(
- function(i) {
- var pair = i.split('=');
- var name = pair[0].trim().toLowerCase();
+ function (i) {
+ const pair = i.split('=');
+ const name = pair[0].trim().toLowerCase();
if (name === this._name) {
if (pair.length === 1 || pair[1].length === 0)
return;
this._hash = JSON.parse(decodeURIComponent(pair[1]));
return;
};
- }
- );
+ },
+ this);
}
});