UNPKG

@miyauci/memo

Version:

Memoization tools, TC39 proposal-function-memo implementation

24 lines (23 loc) 938 B
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license. // This module is browser compatible. // deno-lint-ignore-file ban-types no-explicit-any import { compositeKey, emplace } from "./deps.js"; export function memo(fn, cache = new WeakMap(), keying) { const proxy = new Proxy(fn, { apply(target, thisArg, args) { const key = compositeKey(target, thisArg, ...keying ? keying(args) : args); const value = emplace(cache, key, { insert: () => Reflect.apply(target, thisArg, args), }); return value; }, construct(target, args, newTarget) { const key = compositeKey(target, newTarget, ...keying ? keying(args) : args); const value = emplace(cache, key, { insert: () => Reflect.construct(target, args, newTarget), }); return value; }, }); return proxy; }