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

Function createCachedBounds

lib/core/createCachedBounds.ts:4–70  ·  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 let bounds = cache.get(index);
23 if (bounds === undefined) {
24 bounds = { size: itemSize, scrollOffset: index * itemSize };
25 cache.set(index, bounds);
26 }
27 return bounds;
28 }
29
30 while (cache.size - 1 < index) {
31 const currentIndex = cache.size;
32
33 const size = itemSize(currentIndex, itemProps);
34
35 if (currentIndex === 0) {
36 cache.set(currentIndex, {
37 size,
38 scrollOffset: 0
39 });
40 } else {
41 const previousRowBounds = cache.get(currentIndex - 1);
42 assert(
43 previousRowBounds !== undefined,
44 `Unexpected bounds cache miss for index ${index}`
45 );
46
47 cache.set(currentIndex, {
48 scrollOffset:
49 previousRowBounds.scrollOffset + previousRowBounds.size,
50 size
51 });
52 }
53 }
54
55 const bounds = cache.get(index);
56 assert(
57 bounds !== undefined,
58 `Unexpected bounds cache miss for index ${index}`
59 );
60
61 return bounds;

Callers 6

getIndicesFunction · 0.90
useCachedBoundsFunction · 0.90

Calls

no outgoing calls

Tested by 1

getIndicesFunction · 0.72