Skip to content

Commit

Permalink
Change cache generation to useRef
Browse files Browse the repository at this point in the history
  • Loading branch information
lxsmnsyc committed May 16, 2023
1 parent 1645c4d commit e288b04
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
13 changes: 10 additions & 3 deletions packages/forgetti/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@ export function $$equals(cache: unknown[], index: number, b: unknown): boolean {
return index in cache && isEqual(cache[index], b);
}

export type MemoHook = <T>(callback: () => T, dependencies: unknown[]) => T;
export interface Ref<T> {
current: T;
}
export type RefHook = <T>(callback: T) => Ref<T>;

export function $$cache(hook: MemoHook, size: number): unknown[] {
return hook(() => new Array<unknown>(size), []);
export function $$cache(hook: RefHook, size: number): unknown[] {
const ref = hook<unknown[] | undefined>(undefined);
if (!ref.current) {
ref.current = new Array(size);
}
return ref.current;
}

export function $$branch(parent: unknown[], index: number, size: number): unknown[] {
Expand Down
2 changes: 1 addition & 1 deletion packages/forgetti/src/core/optimizer-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export default class OptimizerScope {
getImportIdentifier(
this.ctx,
this.path,
this.ctx.preset.runtime.useMemo,
this.ctx.preset.runtime.useRef,
),
t.numericLiteral(this.indeces),
],
Expand Down
10 changes: 5 additions & 5 deletions packages/forgetti/src/core/presets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface Preset {
hook?: RawRegExp;
};
runtime: {
useMemo: ImportRegistration;
useRef: ImportRegistration;
memo: ImportRegistration;
};
imports: {
Expand Down Expand Up @@ -57,8 +57,8 @@ export const PRESETS = {
},
},
runtime: {
useMemo: {
name: 'useMemo',
useRef: {
name: 'useRef',
source: 'react',
kind: 'named',
},
Expand Down Expand Up @@ -134,8 +134,8 @@ export const PRESETS = {
},
},
runtime: {
useMemo: {
name: 'useMemo',
useRef: {
name: 'useRef',
source: 'preact/hooks',
kind: 'named',
},
Expand Down

0 comments on commit e288b04

Please sign in to comment.