Skip to content

Instantly share code, notes, and snippets.

@ihsanbudiman
Created January 9, 2022 07:16
Show Gist options
  • Save ihsanbudiman/68ad60722c50115403c840dfe88fa71e to your computer and use it in GitHub Desktop.
Save ihsanbudiman/68ad60722c50115403c840dfe88fa71e to your computer and use it in GitHub Desktop.
looping data yang mempunyai detail
const { performance } = require("perf_hooks");
// biasanya ini terjadi di website POS dimana
// ada laporan yang harus group sesuai master nya
// lalu keluarin detailnya
// ========= start fill data master + detail ============
const masters = [];
const details = [];
for (let i = 0; i < 5000; i++) {
masters.push({
id: i,
data_master: "blabla",
});
for (let j = 0; j < 2; j++) {
details.push({
id_master: i,
data_detail: "blalbalba",
});
}
}
// ========= end fill data master + detail ============
// ========= start loop ============
let startTime1 = performance.now();
masters.forEach((m) => {
// do something
details.forEach((d) => {
// data diambil dengan loop jika detail.id_master nya = master.id O(n)
if (d.id_master === m.id) {
// do something
}
});
});
let endTime1 = performance.now();
let time1 = (endTime1 - startTime1) / 1000;
console.log(`hasil tanpa map ${time1}`);
// ========= end loop ============
let startTime2 = performance.now();
// ========= start pindahin data ke map ============
let newMap = {};
details.forEach((d) => {
if (!newMap[d.id_master]) {
newMap[d.id_master] = [];
}
newMap[d.id_master].push(d);
// console.log(newMap[d.id_master]);
});
// ========= end pindahin data ke map ============
// ========= start loop ============
masters.forEach((m) => {
// do something
// data diambil dari map yang mempunyai index / nama field id master O(1)
const det = newMap[m.id];
det.forEach((d) => {
// do something
});
});
// ========= end loop ============
let endTime2 = performance.now();
let time2 = (endTime2 - startTime2) / 1000;
console.log(`hasil dengan map ${time2}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment