Skip to content
This repository has been archived by the owner on Aug 9, 2024. It is now read-only.

Commit

Permalink
feat: grabItems method
Browse files Browse the repository at this point in the history
  • Loading branch information
Kelin2025 committed Jul 7, 2023
1 parent 3f8d66d commit 104dc57
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions packages/core/src/grabItems.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { NoInfer, combine } from "effector";
import { Compute } from "ts-toolbelt/out/Any/Compute";
import { createMap } from "./createMap";
import { ListApi, Mapping, PossibleKey, Selection } from "./types";

type ValueByType<T, U extends keyof T> = {
[P in U]: { type: P; value: T[P] }
}[U]

export const grabItems = <Item, Key extends PossibleKey, Shape>(
kv: ListApi<Item, Key> | Selection<Item, Key> | Mapping<Item, Key>,
config: {
source: {
[ShapeKey in keyof Shape]:
| ListApi<Shape[ShapeKey], string>
| Selection<Shape[ShapeKey], string>
| Mapping<Shape[ShapeKey], string>
}
filter: NoInfer<{
[ShapeKey in keyof Shape]: (entry: Shape[ShapeKey], item: Item) => boolean
}>
orderBy?:
| {
key: keyof Shape[keyof Shape]
type: 'asc' | 'desc'
}
| ((item: Item) => {
key: keyof Shape[keyof Shape]
type: 'asc' | 'desc'
})
},
) => {
return createMap(kv, {
source: combine(
Object.fromEntries(Object.entries(config.source).map(([key, kv]) => [key, kv.state.store])),
),
fn: (item, source) => {
const children = [] as Compute<ValueByType<Shape, keyof Shape>[], 'flat'>
for (const shapeKey in source) {
children.push(
// @ts-expect-error ...
...Object.values(source[shapeKey].ref)
// @ts-expect-error ...
.filter((shapeItem) => config.filter[shapeKey](shapeItem, item))
.map((value) => ({ type: shapeKey, value })),
)
}
const orderBy = !config.orderBy
? null
: typeof config.orderBy === 'function'
? config.orderBy(item)
: config.orderBy
return {
item,
children: orderBy
? children.sort((a, b) => {
return orderBy.type === 'asc'
? +a.value[orderBy.key] - +b.value[orderBy.key]
: +b.value[orderBy.key] - +a.value[orderBy.key]
})
: children,
}
},
})
}

0 comments on commit 104dc57

Please sign in to comment.