Skip to content

Instantly share code, notes, and snippets.

@chibat
Last active June 30, 2018 16:15
Show Gist options
  • Save chibat/a4a88bb65c7bb719945e4acc907bed62 to your computer and use it in GitHub Desktop.
Save chibat/a4a88bb65c7bb719945e4acc907bed62 to your computer and use it in GitHub Desktop.
typescript, javascript で Set, Map を json text にシリアライズしてデシリアライズする
function stringify(map: Set<any> | Map<any, any>) {
return JSON.stringify(Array.from(map));
}
function newSet<T>(text: string): Set<T> {
return new Set<T>(JSON.parse(text));
}
function newMap<K, V>(text: string) {
return new Map<K, V>(JSON.parse(text));
}
{
const set = new Set<number>([1, 2]);
console.info(set);
const text = stringify(set);
console.info(text);
console.info(newSet<number>(text));
}
{
const map = new Map<string, number>([['key1', 1], ['key2', 2]]);
console.info(map);
const text = stringify(map);
console.info(text);
console.info(newMap<string, number>(text));
}
@chibat
Copy link
Author

chibat commented Jun 30, 2018

test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment