3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScript/JavaScript でメモ化する

Last updated at Posted at 2020-08-19

例1. TypeScript

引数に function を渡す。
二回目以降の呼び出しでは、引数の function、またはその引数(ここでは data)にアクセス出来ない状況を想定。

定義

type ValidationResponse = {
  valid: boolean
  errors: string[]
}

const validator = (
  validatorFn?: () => ValidationResponse
): ValidationResponse => {
  if (!validator.result['cached'] && validatorFn) {
    validator.result['cached'] = validatorFn()
  }

  return validator.result['cached']
}
validator.result = {}

呼び出し

// 一度目
// 引数(validatorFn)を渡す。
const { valid } = validator(() => validatorFn(data))

// 二度目
// 引数(validatorFn)を渡さない。
const { errors } = validator()

例2. JavaScript

var myFunc = function (param) {
  if (!myFunc.cache[param]) {
    var result = [];
    // 重たい処理
    myFunc.cache[param] = result;
  }
  return myFunc.cache[param];
};
// キャッシュ
myFunc.cache = {};

JavaScriptパターン p79 より引用。

3
3
0

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?