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 85333a9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
11 changes: 9 additions & 2 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 @@ -167,9 +167,16 @@ 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]!;

// 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 85333a9

Please sign in to comment.