Skip to content

Instantly share code, notes, and snippets.

@karimsa
Created October 1, 2018 16:10
Show Gist options
  • Save karimsa/0b26e8ec20bbb3cceb48bbc959a403fc to your computer and use it in GitHub Desktop.
Save karimsa/0b26e8ec20bbb3cceb48bbc959a403fc to your computer and use it in GitHub Desktop.
Serialize an ES2015 Map object to a JSON object
/**
* 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