Yomguithereal / mnemonist

Curated collection of data structures for the JavaScript/TypeScript language.
https://yomguithereal.github.io/mnemonist
MIT License
2.28k stars 92 forks source link

MultiSet.toJSON output is surprising #204

Closed kberg closed 2 years ago

kberg commented 2 years ago

Granted, it's not documented, but...

const s = new MultiSet<string>();
s.add('a', 2);
console.log(s.get('a'));
console.log(JSON.stringify(s.toJSON()));

generates

2
{}

I expected something like

2
{a: 2}
kberg commented 2 years ago

PS

console.log(JSON.stringify(Array.from(s.toJSON())));

generates

[["a",2]]
Yomguithereal commented 2 years ago

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.

kberg commented 2 years ago

I see. What's the value of toJSON, then?

kberg commented 2 years ago

(You can ignore my question if you like.)

Yomguithereal commented 2 years ago

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.