Improve state serialization
Change-Id: Ic9d9b791c548827028cbbd4c57751b0c88c8c265
diff --git a/dev/js/spec/stateSpec.js b/dev/js/spec/stateSpec.js
index 286cb1c..5fb6e71 100644
--- a/dev/js/spec/stateSpec.js
+++ b/dev/js/spec/stateSpec.js
@@ -140,44 +140,71 @@
describe('KorAP.State.Manager', function () {
- const el = document.createElement('input');
-
it('should be initializable', function () {
+ const el = document.createElement('input');
let sm = stateManagerClass.create(el);
expect(sm).toBeTruthy();
- expect(sm.toString()).toEqual("{}");
+ expect(sm.toString()).toEqual("");
});
it('should be extensible', function () {
+
+ const el = document.createElement('input');
const sm = stateManagerClass.create(el);
expect(sm).toBeTruthy();
const s1 = sm.newState('test', [1,2,3]);
- expect(sm.toString()).toEqual("{}");
+ expect(sm.toString()).toEqual("");
s1.set(2);
- expect(sm.toString()).toEqual("{\"test\":2}");
+ expect(sm.toString()).toEqual("\"test\":2");
s1.set(3);
- expect(sm.toString()).toEqual("{\"test\":3}");
+ expect(sm.toString()).toEqual("\"test\":3");
const s2 = sm.newState('glemm', [true,false]);
- let serial = JSON.parse(sm.toString());
+ let serial = JSON.parse('{' + sm.toString() + '}');
expect(serial["test"]).toEqual(3);
expect(serial["glemm"]).toBeUndefined();
s2.set(false);
- serial = JSON.parse(sm.toString());
+ serial = JSON.parse('{' + sm.toString() + '}');
expect(serial["test"]).toEqual(3);
expect(serial["glemm"]).toEqual(false);
});
+
+
+ it('should serialize correctly', function () {
+ const el = document.createElement('input');
+ const sm = stateManagerClass.create(el);
+ expect(sm).toBeTruthy();
+
+ const s1 = sm.newState('x', [1,2,3]);
+
+ expect(sm.toString()).toEqual("");
+
+ s1.set(2);
+
+ expect(sm.toString()).toEqual("\"x\":2");
+
+ const s2 = sm.newState('y', [true,false]);
+ s2.set(false)
+
+ const s3 = sm.newState('z', ['a','b','c']);
+ s3.set('b')
+
+ expect(sm.toString().indexOf("\"x\":2")).not.toEqual(-1);
+ expect(sm.toString().indexOf("\"y\":false")).not.toEqual(-1);
+ expect(sm.toString().indexOf("\"z\":\"b\"")).not.toEqual(-1);
+ expect(sm.toString().indexOf("\"a\":\"d\"")).toEqual(-1);
+ });
});
});
diff --git a/dev/js/src/state/manager.js b/dev/js/src/state/manager.js
index 26cb482..6d7fe11 100644
--- a/dev/js/src/state/manager.js
+++ b/dev/js/src/state/manager.js
@@ -37,13 +37,17 @@
- this._states = JSON.parse(value);
+ this._states = JSON.parse('{' + value + '}');
},
// Return the string representation of all states
toString : function () {
- return JSON.stringify(this._states);
+
+ if (this._states.size === 0)
+ return undefined;
+
+ return JSON.stringify(this._states).slice(1,-1);
},