Created
October 1, 2018 16:10
-
-
Save karimsa/0b26e8ec20bbb3cceb48bbc959a403fc to your computer and use it in GitHub Desktop.
Serialize an ES2015 Map object to a JSON object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Serialize map to object. Goal is to be able to use 'Map' over object when performing | |
* large algorithms over a hash map - but then serializing it to an object for sending | |
* over a wire. | |
*/ | |
Map.prototype.toJSON = function() { | |
const o = Object.create(null) | |
for (const k of this.keys()) { | |
if (typeof k !== 'string' && typeof k !== 'number') { | |
throw new Error(`Cannot serialize a map with a key of type: ${typeof k}`) | |
} | |
o[k] = this.get(k) | |
} | |
return o | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment