Created
February 12, 2024 11:53
-
-
Save Drag13/c4a7e5f2dd9dc1667c3eeb8bb4e0e3bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SETUP | |
function generateData(n) { | |
const ids = new Array(n).fill(0).map((_, i) => i); | |
return { | |
notebooks: ids.map((x) => ({ id: x })), | |
prices: ids | |
.map((x) => [ | |
{ | |
entityId: x, | |
price: 100, | |
timestamp: new Date(), | |
}, | |
{ | |
entityId: x, | |
price: 200, | |
timestamp: new Date(), | |
}, | |
{ | |
entityId: x, | |
price: 300, | |
timestamp: new Date(), | |
}, | |
]) | |
.flat(), | |
}; | |
} | |
function getNotebooksWithPriceNaive(notes, prices) { | |
return notes.map((notebook) => ({ | |
...notebook, | |
price: prices.filter((x) => x.entityId === notebook.id), | |
})); | |
} | |
function getNotebooksWithPriceMap(notes, prices) { | |
const pricesMap = prices.reduce((acc, price) => { | |
if (acc.has(price.entityId)) { | |
acc.get(price.entityId)?.push(price); | |
} else { | |
acc.set(price.entityId, [price]); | |
} | |
return acc; | |
}, new Map()); | |
return notes.map((notebook) => ({ | |
...notebook, | |
prices: pricesMap.get(notebook.id), | |
})); | |
} | |
const { notebooks, prices } = generateData(300); | |
// TEST1 - NAIVE | |
const res1 = getNotebooksWithPriceNaive(notebooks, prices); | |
// TEST2 - MAP | |
const res2 = getNotebooksWithPriceMap(notebooks, prices); | |
console.log(res1); | |
console.log(res2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment