JS - Better JSON stringify for Map/Set

by PhilQ

HTML

<pre id="code"></pre>

JavaScript

const array1 = [1, 'a', 'false', false, null, undefined];

const object1 = { x: -1, y: 0, z: 1 };

const set1 = new Set();
set1.add(11);
set1.add(22);
set1.add(33);

const map1 = new Map();
map1.set('foo', 'bar');
map1.set(100, 200);

document.getElementById('code').innerHTML = JSON.stringify(
    [array1, object1, set1, map1],
    (key, value) => {
    	return (
          (value instanceof Set) ? Array.from(value) :
          (value instanceof Map) ? Object.fromEntries(value) :
          value
        );
    }
  );

// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#using_json.stringify
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_reviver_when_paired_with_the_replacer_of_json.stringify