Skip to content

Instantly share code, notes, and snippets.

@Drag13
Created February 12, 2024 11:53
Show Gist options
  • Save Drag13/c4a7e5f2dd9dc1667c3eeb8bb4e0e3bc to your computer and use it in GitHub Desktop.
Save Drag13/c4a7e5f2dd9dc1667c3eeb8bb4e0e3bc to your computer and use it in GitHub Desktop.

Revisions

  1. Drag13 created this gist Feb 12, 2024.
    62 changes: 62 additions & 0 deletions perftest.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    // 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);