Skip to content

Commit

Permalink
Support serializing Map and Set objects.
Browse files Browse the repository at this point in the history
These container types are especially interesting because they can contain
indirect references to themselves!
  • Loading branch information
benjamn committed Feb 15, 2016
1 parent 7c4af1f commit b6ce5ca
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
36 changes: 36 additions & 0 deletions custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,39 @@ arson.registerType("RegExp", {
return args && new RegExp(args[0], args[1]);
}
});

typeof Set === "function" &&
arson.registerType("Set", {
deconstruct: function (set) {
if (toString.call(set) === setTag) {
return Array.from(set);
}
},

reconstruct: function (values) {
if (values) {
values.forEach(this.add, this);
} else {
return new Set;
}
}
});

typeof Map === "function" &&
arson.registerType("Map", {
deconstruct: function (map) {
if (toString.call(map) === mapTag) {
return Array.from(map);
}
},

reconstruct: function (entries) {
if (entries) {
entries.forEach(function (entry) {
this.set(entry[0], entry[1]);
}, this);
} else {
return new Map;
}
}
});
30 changes: 30 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,36 @@ describe("encoding and decoding", function () {
assert.strictEqual(bb[0].toString("utf8"), "asdf");
});

it("should work with Map objects", function () {
var m1 = new Map;
var value = { foo: 42 };
m1.set(1234, value);
m1.set(value, m1);
m1.set(m1, "self");
assert.strictEqual(m1.get(m1.get(1234)), m1);
var m2 = arson.decode(arson.encode(m1));
assert.strictEqual(m2.get(m2.get(1234)), m2);
assert.strictEqual(m2.get(m2), "self");
});

it("should work with Set objects", function () {
var s1 = new Set;
s1.add(s1);

var s2 = arson.decode(arson.encode(s1));
assert.strictEqual(Array.from(s2)[0], s2);
s2.add(s1);

var s3 = arson.decode(arson.encode(s2));
var elems = Array.from(s3);

assert.strictEqual(elems.length, 2);
assert.notStrictEqual(elems[0], elems[1]);
elems.forEach(function (s) {
assert.ok(s.has(s));
});
});

it("should work for sparse arrays", function () {
function check(array) {
assert.deepEqual(array, arson.decode(arson.encode(array)));
Expand Down

0 comments on commit b6ce5ca

Please sign in to comment.