De-yu's Note
  • Deyu Notebook
  • Side Project
    • Stock
    • ChatBox
    • SnowCraft
    • ScrollBar
  • 架構問題
    • 解決 RTK Query data 為 undefined 的實務做法
    • 透過 xstate 解決UI 狀態問題
  • 技術觀點
    • 為什麼需要 store
    • Router 作用
    • react 和 next.js 差異
    • monoRepo vs Multiple Repo
  • Performance
    • React 優化
  • JS Coding
    • Curry
    • Debounce
    • Throttle
  • map
  • memo()
  • Promise 實作
  • Promise Function
  • Testing
    • 使用 Jest 、 React Testing Library 、MSW 建立測試環境
  • Miscellaneous
    • Event Loop
    • Browser
    • Code Review
    • Storage
  • AMD 、 CommonJS 、 ES modules
  • JWT
  • Next.js
  • 用過的 module
  • Internet
    • UDP
  • TCP/IP
  • SSL TLS
  • HTTP
  • AI 工作流
    • Page 1
Powered by GitBook
On this page

memo()


題目: 近似於 React.memo
如果帶入相同的參數則不重新計算結果

const func = (arg1, arg2) => {
  return arg1 + arg2
}
const memoed = memo(func)
memoed(1, 2) 
// 3, func is called
memoed(1, 2) 
// 3 is returned right away without calling func

function memo<T extends (...args: any[]) => any>(func: T, resolver?: (...args: Parameters<T>) => string): T {
  // your code here
   let map = new Map<string, any>()

  function resolve (args: Parameters<T>): string {
    if(resolver === undefined) {
      return args.toString()
    }
    return resolver(...args)
    
  }
  
  const memoizedFunc = function(this: any, ...args: Parameters<T>): ReturnType<T> {
    if(map.has(resolve(args))) {
      return map.get(resolve(args))
    } else {
      const value = func.call(this, ...args)
      map.set(resolve(args), value)
      return value;
    }
  }

  return memoizedFunc as T;
}


PreviousmapNextPromise 實作

Last updated 28 days ago