MCPcopy Create free account
hub / github.com/bvaughn/react-window / createCachedBounds

Function createCachedBounds

lib/core/createCachedBounds.ts:4–65  ·  view source on GitHub ↗
({
  itemCount,
  itemProps,
  itemSize
}: {
  itemCount: number;
  itemProps: Props;
  itemSize: number | SizeFunction<Props>;
})

Source from the content-addressed store, hash-verified

2import type { Bounds, CachedBounds, SizeFunction } from "./types";
3
4export function createCachedBounds<Props extends object>({
5 itemCount,
6 itemProps,
7 itemSize
8}: {
9 itemCount: number;
10 itemProps: Props;
11 itemSize: number | SizeFunction<Props>;
12}): CachedBounds {
13 const cache = new Map<number, Bounds>();
14
15 return {
16 itemSize: typeof itemSize === "number" ? itemSize : undefined,
17 get(index: number) {
18 assert(index < itemCount, `Invalid index ${index}`);
19
20 if (typeof itemSize === "number") {
21 assert(index >= 0, `Invalid index ${index}`);
22 return { size: itemSize, scrollOffset: index * itemSize };
23 }
24
25 while (cache.size - 1 < index) {
26 const currentIndex = cache.size;
27
28 const size = itemSize(currentIndex, itemProps);
29
30 if (currentIndex === 0) {
31 cache.set(currentIndex, {
32 size,
33 scrollOffset: 0
34 });
35 } else {
36 const previousRowBounds = cache.get(currentIndex - 1);
37 assert(
38 previousRowBounds !== undefined,
39 `Unexpected bounds cache miss for index ${index}`
40 );
41
42 cache.set(currentIndex, {
43 scrollOffset:
44 previousRowBounds.scrollOffset + previousRowBounds.size,
45 size
46 });
47 }
48 }
49
50 const bounds = cache.get(index);
51 assert(
52 bounds !== undefined,
53 `Unexpected bounds cache miss for index ${index}`
54 );
55
56 return bounds;
57 },
58 set(index: number, bounds: Bounds) {
59 cache.set(index, bounds);
60 },
61 get size() {

Callers 6

getIndicesFunction · 0.90
useCachedBoundsFunction · 0.90

Calls

no outgoing calls

Tested by 1

getIndicesFunction · 0.72