Closed kberg closed 2 years ago
PS
console.log(JSON.stringify(Array.from(s.toJSON())));
generates
[["a",2]]
Hello @kberg, this follows the same weird (but explainable) behavior than an ES6's Set. Try for instance:
JSON.stringify(new Set([2]));
// By the way, JSON.stringify automatically calls any toJSON method for you
The reason is that you could use arbitrary keys, even keys that are not JSON-serializable. To this end, ES6 does not JSON-stringifies Set nor Map and ask you to define how you want to do it, a bit like you are doing with your second example that serializes the entries of the multiset.
I see. What's the value of toJSON, then?
(You can ignore my question if you like.)
I see. What's the value of toJSON, then?
In this particular case (the MultiSet) one, not much I am afraid. I just replicated ES6's one in case the specs would change (at that time it was still possible).
The fact is there is no way to serialize some things with JSON and a Set that would rely on object references is one.
Granted, it's not documented, but...
generates
I expected something like