Skip to content

Commit

Permalink
Unuse range
Browse files Browse the repository at this point in the history
  • Loading branch information
inokawa committed Jul 23, 2023
1 parent e3a5fe1 commit b58a03a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 28 deletions.
9 changes: 8 additions & 1 deletion src/core/cache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ import {
hasUnmeasuredItemsInRange,
} from "./cache";
import type { Writeable } from "./types";
import { range } from "./utils";

const range = <T>(length: number, cb: (i: number) => T): T[] => {
const array: T[] = [];
for (let i = 0; i < length; i++) {
array.push(cb(i));
}
return array;
};

const sum = (cache: readonly number[]): number => {
return cache.reduce((acc, c) => acc + c, 0);
Expand Down
37 changes: 18 additions & 19 deletions src/core/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { DeepReadonly, Writeable } from "./types";
import { exists, max, median, min, range } from "./utils";
import { exists, max, median, min } from "./utils";

export const UNCACHED = -1;

Expand Down Expand Up @@ -138,29 +138,28 @@ export const resetCache = (
itemSize: number,
cache?: Cache
): Cache => {
const sizes: number[] = [];
const offsets: number[] = [];
for (let i = 0; i < length; i++) {
const size = cache && cache._sizes[i];
sizes.push(exists(size) ? size : UNCACHED);

if (i === 0) {
// first offset must be 0
offsets.push(0);
} else {
const offset = cache && cache._offsets[i];
offsets.push(exists(offset) ? offset : UNCACHED);
}
}

return {
_defaultItemSize: cache ? cache._defaultItemSize : itemSize,
_length: length,
_measuredOffsetIndex: cache
? min(cache._measuredOffsetIndex, length - 1)
: 0,
_sizes: range(length, (i) => {
const size = cache && cache._sizes[i];
if (exists(size)) {
return size;
}
return UNCACHED;
}),
_offsets: range(length, (i) => {
if (i === 0) {
// first offset must be 0
return 0;
}
const offset = cache && cache._offsets[i];
if (exists(offset)) {
return offset;
}
return UNCACHED;
}),
_sizes: sizes,
_offsets: offsets,
};
};
8 changes: 0 additions & 8 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,6 @@ export const timeout = setTimeout;

export const exists = <T>(v: T): v is Exclude<T, null | undefined> => v != null;

export const range = <T>(length: number, cb: (i: number) => T): T[] => {
const array: T[] = [];
for (let i = 0; i < length; i++) {
array.push(cb(i));
}
return array;
};

export const median = (arr: number[]): number => {
const s = [...arr].sort((a, b) => a - b);
const mid = (arr.length / 2) | 0;
Expand Down

0 comments on commit b58a03a

Please sign in to comment.