Help us understand the problem. What is going on with this article?

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

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

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)) // 同上

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

suin
Qiita 4位/TypeScript入門書執筆中/TypeScripterのための座談会「YYTypeScript」主催/『実践ドメイン駆動設計』書籍邦訳レビュア/分報Slack考案/YYPHP主催/CodeIQマガジン執筆/株式会社クラフトマンソフトウェア創設/Web自動テスト「ShouldBee」の開発/TypeScript/DDD/OOP
https://yyts.connpass.com/
shouldbee
開発者向けテスト支援サービスShouldBeeを開発・運営するスタートアップ(onlab第8期)
http://shouldbee.at
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした