Skip to content

Instantly share code, notes, and snippets.

@artem-mangilev
Last active March 23, 2022 10:01
Show Gist options
  • Save artem-mangilev/83c421609d6863e39a90a2574822ee6b to your computer and use it in GitHub Desktop.
Save artem-mangilev/83c421609d6863e39a90a2574822ee6b to your computer and use it in GitHub Desktop.
JSON -> Map
// const { performance } = require('perf_hooks'); // for node.js
function map(strings, ...values) {
const innerMapsMap = new Map<string, Map<any, any>>();
let str = ''
strings.forEach((string, i) => {
if (values[i] instanceof Map)
{
const key = `__innerMap_${performance.now()}`
innerMapsMap.set(key, values[i]);
str += string + key;
} else if (values[i] === undefined) {
str += string;
}
})
const obj = JSON.parse(str);
const mapify = (obj) => {
const map = new Map();
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
map.set(key, mapify(obj[key]));
} else if (typeof obj[key] === 'string' && obj[key].startsWith('__innerMap_')) {
map.set(key, innerMapsMap.get(obj[key]));
} else if (key.startsWith('__innerMap_')) {
map.set(innerMapsMap.get(key), obj[key]);
} else {
map.set(key, obj[key]);
}
}
}
return map;
}
return mapify(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment