Skip to content

Open source personal finance application

perf: merge getTrnsIds 5-pass filter chain into single pass

Ilya Komichevc3f99c2a13a2
diff --git a/app/components/trns/getTrns.ts b/app/components/trns/getTrns.ts
index 338dcb3d..c4c7efcd 100644
--- a/app/components/trns/getTrns.ts
+++ b/app/components/trns/getTrns.ts
@@ -9,38 +9,29 @@ export function getTrnsIds(props: TrnsGetterProps) {
const walletsSet = props.walletsIds?.length ? new Set(props.walletsIds) : null
const categoriesSet = props.categoriesIds?.length ? new Set(props.categoriesIds) : null
const typesSet = Array.isArray(props.trnsTypes) ? new Set(props.trnsTypes) : null
-
- const filters: Array<(ids: TrnId[]) => TrnId[]> = [
- // Types filter
- ids => typesSet
- ? ids.filter(id => typesSet.has(props.trnsItems?.[id]?.type))
- : ids,
-
- // Date filters
- ids => props.dates?.from
- ? ids.filter(id => props.trnsItems?.[id]?.date >= props.dates.from)
- : ids,
- ids => props.dates?.until
- ? ids.filter(id => props.trnsItems?.[id]?.date <= props.dates.until)
- : ids,
-
- // Wallet filter
- ids => walletsSet
- ? ids.filter((id) => {
- const trn = props.trnsItems?.[id]
- return walletsSet.has(trn?.walletId)
- || walletsSet.has(trn?.expenseWalletId)
- || walletsSet.has(trn?.incomeWalletId)
- })
- : ids,
-
- // Category filter
- ids => categoriesSet
- ? ids.filter(id => categoriesSet.has(props.trnsItems?.[id]?.categoryId))
- : ids,
- ]
-
- const result = filters.reduce((ids, filter) => filter(ids), trnsIds)
+ const from = props.dates?.from
+ const until = props.dates?.until
+
+ const hasFilters = typesSet || from || until || walletsSet || categoriesSet
+
+ const result = hasFilters
+ ? trnsIds.filter((id) => {
+ const trn = props.trnsItems?.[id]
+ if (!trn)
+ return false
+ if (typesSet && !typesSet.has(trn.type))
+ return false
+ if (from && trn.date < from)
+ return false
+ if (until && trn.date > until)
+ return false
+ if (walletsSet && !walletsSet.has(trn.walletId) && !walletsSet.has(trn.expenseWalletId) && !walletsSet.has(trn.incomeWalletId))
+ return false
+ if (categoriesSet && !categoriesSet.has(trn.categoryId))
+ return false
+ return true
+ })
+ : trnsIds
if (props.sort)
result.sort((a, b) => props.trnsItems?.[b]?.date - props.trnsItems?.[a]?.date)