LoginSignup
31
28

More than 3 years have passed since last update.

TypeScript: 計算結果をキャッシュする関数

Last updated at Posted at 2020-03-06

ここで紹介するのは、「計算結果をキャッシュし、二回目以降はキャッシュされた計算結果を返す」といった特性を普通の関数に付与する便利関数です。

const none = Symbol()
function cache<T extends (...args: any[]) => any>(
  func: T,
): (...args: Parameters<T>) => ReturnType<T> {
  let ret: ReturnType<T> | typeof none = none
  return (...args) => ret === none ? ret = func(...args) : ret
}

使い方

// すごく計算に時間を要する関数
function fibonacci(num: number): number {
  if (num <= 1) return 1;
  return fibonacci(num - 1) + fibonacci(num - 2);
}

// キャッシュ機能を付与した関数を作る
const cachedFibonacci = cache(fibonacci)
console.log(cachedFibonacci(40)) // ここで計算して結果を返す
console.log(cachedFibonacci(40)) // キャッシュから計算結果を返す
console.log(cachedFibonacci(40)) // 同上

引数をキャッシュするのを忘れてたので、後で直します。

31
28
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
28