Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
inokawa committed Nov 26, 2024
1 parent c7c6461 commit ffff09c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
14 changes: 11 additions & 3 deletions src/core/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type InternalCacheSnapshot, type ItemsRange } from "./types";
import { clamp, floor, max, median, min } from "./utils";
import { clamp, floor, max, min, sort } from "./utils";

type Writeable<T> = {
-readonly [key in keyof T]: Writeable<T[key]>;
Expand Down Expand Up @@ -153,7 +153,6 @@ export const estimateDefaultItemSize = (
): number => {
let measuredCountBeforeStart = 0;
// This function will be called after measurement so measured size array must be longer than 0
const prevDefaultItemSize = cache._defaultItemSize;
const measuredSizes: number[] = [];
cache._sizes.forEach((s, i) => {
if (s !== UNCACHED) {
Expand All @@ -167,9 +166,18 @@ export const estimateDefaultItemSize = (
// Discard cache for now
cache._computedOffsetIndex = -1;

// Calculate median
const sorted = sort(measuredSizes);
const len = sorted.length;
const mid = (len / 2) | 0;
const median =
len % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;

const prevDefaultItemSize = cache._defaultItemSize;

// Calculate diff of unmeasured items before start
return (
((cache._defaultItemSize = median(measuredSizes)) - prevDefaultItemSize) *
((cache._defaultItemSize = median) - prevDefaultItemSize) *
max(startIndex - measuredCountBeforeStart, 0)
);
};
Expand Down
11 changes: 0 additions & 11 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,6 @@ export const sort = <T extends number>(arr: readonly T[]): T[] => {
return [...arr].sort((a, b) => a - b);
};

/**
* @internal
*/
export const median = (arr: number[]): number => {
const sorted = sort(arr);
const mid = (arr.length / 2) | 0;
return sorted.length % 2 === 0
? (sorted[mid - 1]! + sorted[mid]!) / 2
: sorted[mid]!;
};

/**
* @internal
*/
Expand Down

0 comments on commit ffff09c

Please sign in to comment.