Skip to content

Instantly share code, notes, and snippets.

@tatupesonen
Last active January 11, 2022 09:02
Show Gist options
  • Save tatupesonen/890b9f6140114d3827f4299d6af6a92f to your computer and use it in GitHub Desktop.
Save tatupesonen/890b9f6140114d3827f4299d6af6a92f to your computer and use it in GitHub Desktop.
Object specific merge
const util = require("util");
const { performance } = require("perf_hooks");
// Input data is like this
const exampleInput = [
{ 9668: { "Fa0/11": { in_traffic: "1000" } } },
{ 9668: { "Fa0/11": { out_traffic: "900" } } },
{ 9628: { "Fa0/16": { in_traffic: "800" } } },
];
// Wanted output:
const output = {
9668: { 'Fa0/11': { in_traffic: '1000', out_traffic: '900' } },
9628: { 'Fa0/16': { in_traffic: '800' } },
};
const merge = (data) => {
//generates hashmap
let hm = {};
for (let i = 0; i < data.length; i++) {
let keyAtIndex = Object.keys(data[i])[0]; //We only need the first and only key
hm[keyAtIndex]
? (hm[keyAtIndex] = [...hm[keyAtIndex], i])
: (hm[keyAtIndex] = [i]);
}
//start merging
let merged = [];
for (let k in hm) {
let arr = hm[k];
let obj = {};
arr.forEach((e) => {
//deep merge
let deepKey = Object.keys(data[e][k])[0];
obj = { ...obj, [deepKey]: { ...obj[deepKey], ...data[e][k][deepKey] } };
});
merged.push({ [k]: obj });
}
return merged;
};
const createBenchmarkData = (n) => {
let data = [];
for (let i = 1; i < n; i++) {
let sameItems = Math.floor(Math.random() * Math.floor(4)) + 1;
for (let j = 1; j <= sameItems; j++) {
data.push({
[i]: {
[`Fa0${i}`]: {
[j % 2 === 0 ? "in_traffic" : "out_traffic"]: i * 1000,
},
},
});
}
}
return data;
};
let data = createBenchmarkData(110000);
let pre = performance.now();
let d = merge(data);
let after = performance.now();
console.log("Length of data pre-merge: ", data.length);
console.log("Length of data post-merge: ", d.length);
console.log(`Merging with n = ${data.length} took ${after - pre} ms`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment