danvk / effective-typescript

Effective TypeScript 2nd Edition: 83 Specific Ways to Improve Your TypeScript
https://effectivetypescript.com
Other
1.56k stars 226 forks source link

The `cacheLast` function is not implemented as expected #17

Closed liby closed 2 years ago

liby commented 2 years ago

ch05-any/item-40-hide-unsafe-casts/hide-unsafe-casts-04.ts

Maybe it would be better to change the name of the function to memorize. cacheLast always sounds confusing.

function cacheLast<T extends Function>(fn: T): T {
  let lastArgs: any[]|null = null;
  let lastResult: any;
  return function(...args: any[]) {
    if (!lastArgs || !shallowEqual(lastArgs, args)) {
      lastResult = fn(...args);
      lastArgs = args;
    }
    return lastResult;
  } as unknown as T;
}

Is it better to use JSON.stringify(args) instead of (lastArgs, args) function?

liby commented 2 years ago

It's not important.