8
1

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 5 years have passed since last update.

Proxyを使って関数の呼び出し回数や全実行結果を取得する

Last updated at Posted at 2018-07-28

proxyを使ってラップしてやると、関数に直接機能を追加しなくても機能を追加できるので便利です。

今回はcall-proxyを使って関数の呼び出し回数や全実行結果を取得します。

akameco/call-proxy: call proxy

yarn add call-proxy
const callProxy = require('call-proxy')

let i = 0
const hello = () => `hello ${++i}`
const x = callProxy(hello)

x()
x()
console.log(x.__times__)
// => 2

x()
console.log(x.__times__)
// => 3

console.log(x.__calls__)
// [ 'hello 1', 'hello 2', 'hello 3' } ]

このように関数に__times____calls__というプロパティを追加します。
__times__は今までの実行回数を取得し、__calls__は今までの実行結果を取得できます。

実行自体は単純で以下の通りです。

module.exports = func => {
  const calls = []
  const handler = {
    apply(target, prop, args) {
      const result = Reflect.apply(target, prop, args)
      calls.push(result)
      return result
    },
    get(target, prop, receiver) {
      if (prop === '__times__') {
        return calls.length
      } else if (prop === '__calls__') {
        return calls
      }
      return Reflect.get(target, prop, receiver)
    },
  }
  return new Proxy(func, handler)
}

akameco/call-proxy: call proxy

関連

【JavaScript】うるせぇお前がGolangになるんだよ - Qiita

【Proxy】JavaScriptでRubyのtimesを使う - Qiita

ちょっと__calls__の結果をこのときから変えた。

8
1
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
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?