Skip to content

Instantly share code, notes, and snippets.

@Drag13
Created February 12, 2024 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drag13/c4a7e5f2dd9dc1667c3eeb8bb4e0e3bc to your computer and use it in GitHub Desktop.
Save Drag13/c4a7e5f2dd9dc1667c3eeb8bb4e0e3bc to your computer and use it in GitHub Desktop.
// 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