私は JavaScript スパイ ライブラリ simple-spyを使用しています。
特定の関数をスパイすると、結果のスパイのアリティは常に 0 になることがわかりました。
これは、このカリー化関数の使用に問題を引き起こし ます。
そこで、スパイ ライブラリにアリティの透過性を追加するプル リクエストを送信しました。
コードは次のようになります。
function spy(fn) {
const inner = (...args) => {
stub.callCount++;
stub.args.push(args);
return fn(...args);
};
// ends up a string like
// 'a,b,c,d'
// depending on the `fn.length`
const stubArgs = Array(fn.length)
.fill(null)
.map((m, i) => String.fromCodePoint(97 + i))
.join();
const stubBody = 'return inner(...arguments);';
// this seems to be the only way
// to create a function with
// programmatically specified arity
const stub = eval(
// the wrapping parens is to
// prevent it from evaluating as
// a function declaration
`(function (${stubArgs}) { ${stubBody} })`
);
stub.reset = () => {
stub.callCount = 0;
stub.args = [];
};
stub.reset();
return stub;
}
exports.spy = spy;
これはうまくいくようです。
を使用せずにこれを行うことは可能eval
ですか?
の使用をeval
これよりもさらに少なくすることは可能ですか?
このスパイの実装には他にも問題があることを認識しています。それは単純化されており、これまでのところ私のユースケースで機能します。