From 67485e98373de0eaa69d87d16db4f1db5f49dc4c Mon Sep 17 00:00:00 2001 From: zkldi Date: Sun, 4 Sep 2022 20:03:31 +0100 Subject: [PATCH] refactor: improve performance of song lookups use lookup tables to optimise looking up songs; the former solution was O(n^2), this one is O(1) with a small hit to memory. --- common/src/utils/util.ts | 10 ++++++++++ .../api/v1/games/_game/_playtype/content/bms-router.ts | 10 ++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/common/src/utils/util.ts b/common/src/utils/util.ts index 376c30834..8e6dd1ba5 100644 --- a/common/src/utils/util.ts +++ b/common/src/utils/util.ts @@ -253,3 +253,13 @@ export function FormatSieglindePMS(sgl: number): string { return `●${(sgl - 12).toFixed(2)}`; } + +export function CreateSongMap(songs: Array>) { + const songMap = new Map>(); + + for (const song of songs) { + songMap.set(song.id, song); + } + + return songMap; +} diff --git a/server/src/server/router/api/v1/games/_game/_playtype/content/bms-router.ts b/server/src/server/router/api/v1/games/_game/_playtype/content/bms-router.ts index a6427bae1..e3ab53774 100644 --- a/server/src/server/router/api/v1/games/_game/_playtype/content/bms-router.ts +++ b/server/src/server/router/api/v1/games/_game/_playtype/content/bms-router.ts @@ -1,6 +1,8 @@ import { Router } from "express"; import db from "external/mongo/db"; import CreateLogCtx from "lib/logger/logger"; +import { CreateSongMap } from "tachi-common"; +import { integer, SongDocument } from "tachi-common/types"; import { GetFolderCharts, GetFoldersFromTable } from "utils/folder"; import { GetTachiData } from "utils/req-tachi-data"; import type { Request, Response } from "express"; @@ -85,10 +87,10 @@ CreateAndMountTable( for (const folder of folders) { const data = await GetFolderCharts(folder, {}, true); const charts = data.charts as Array>; - const songs = data.songs; + const songMap = CreateSongMap(data.songs); for (const chart of charts) { - const song = songs.find((song) => song.id === chart.songID); + const song = songMap.get(chart.songID); if (!song) { response.push({ @@ -146,10 +148,10 @@ CreateAndMountTable( for (const folder of folders) { const data = await GetFolderCharts(folder, {}, true); const charts = data.charts as Array>; - const songs = data.songs; + const songMap = CreateSongMap(data.songs); for (const chart of charts) { - const song = songs.find((song) => song.id === chart.songID); + const song = songMap.get(chart.songID); if (!song) { response.push({