Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
inokawa committed Apr 27, 2024
1 parent d0e956c commit 57345f9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
13 changes: 11 additions & 2 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,22 @@ export const clamp = (
*/
export const exists = <T>(v: T): v is Exclude<T, null | undefined> => v != null;

/**
* @internal
*/
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 s = [...arr].sort((a, b) => a - b);
const sorted = sort(arr);
const mid = (arr.length / 2) | 0;
return s.length % 2 === 0 ? (s[mid - 1]! + s[mid]!) / 2 : s[mid]!;
return sorted.length % 2 === 0
? (sorted[mid - 1]! + sorted[mid]!) / 2
: sorted[mid]!;
};

/**
Expand Down
21 changes: 9 additions & 12 deletions src/react/Virtualizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { flushSync } from "react-dom";
import { useRerender } from "./useRerender";
import { useChildren } from "./useChildren";
import { CustomContainerComponent, CustomItemComponent } from "./types";
import { microtask } from "../core/utils";
import { microtask, sort } from "../core/utils";

/**
* Methods of {@link Virtualizer}.
Expand Down Expand Up @@ -341,17 +341,14 @@ export const Virtualizer = forwardRef<VirtualizerHandle, VirtualizerProps>(
if (keepMounted) {
const startItems: ReactElement[] = [];
const endItems: ReactElement[] = [];
keepMounted
.slice()
.sort((a, b) => a - b)
.forEach((index) => {
if (index < overscanedRangeStart) {
startItems.push(getListItem(index));
}
if (index > overscanedRangeEnd) {
endItems.push(getListItem(index));
}
});
sort(keepMounted).forEach((index) => {
if (index < overscanedRangeStart) {
startItems.push(getListItem(index));
}
if (index > overscanedRangeEnd) {
endItems.push(getListItem(index));
}
});

items.unshift(...startItems);
items.push(...endItems);
Expand Down

0 comments on commit 57345f9

Please sign in to comment.