Skip to content
39 changes: 20 additions & 19 deletions lib/HookCodeFactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class HookCodeFactory {
create(options) {
this.init(options);
let fn;
switch (this.options.type) {
switch (options.type) {
case "sync":
fn = new Function(
this.args(),
Expand Down Expand Up @@ -91,9 +91,10 @@ class HookCodeFactory {
*/
init(options) {
this.options = options;
// slice() avoids the iterator protocol overhead of [...arr].
// eslint-disable-next-line unicorn/prefer-spread
this._args = options.args.slice();
// `_args` is only read (length / join / [0]) - never mutated - so we
// can share the caller's array directly instead of paying for a copy
// on every compile.
this._args = options.args;
this._joinedArgs = undefined;
}

Expand Down Expand Up @@ -454,23 +455,23 @@ class HookCodeFactory {
}

args({ before, after } = {}) {
// Hot during code generation (called once per tap + per interceptor).
// Cache the common no-before/no-after result so we only join once.
if (before === undefined && after === undefined) {
let joined = this._joinedArgs;
if (joined === undefined) {
joined = this._args.length === 0 ? "" : this._args.join(", ");
this._joinedArgs = joined;
}
return joined;
// Hot during code generation. Join `_args` once and cache the result,
// then build the customized variants via string concat instead of
// allocating temporary `[before, ...allArgs]` / `[...allArgs, after]`
// arrays and re-joining.
let joined = this._joinedArgs;
if (joined === undefined) {
joined = this._args.length === 0 ? "" : this._args.join(", ");
this._joinedArgs = joined;
}
let allArgs = this._args;
if (before) allArgs = [before, ...allArgs];
if (after) allArgs = [...allArgs, after];
if (allArgs.length === 0) {
return "";
if (!before && !after) return joined;
if (joined.length === 0) {
if (before && after) return `${before}, ${after}`;
return before || after;
}
return allArgs.join(", ");
if (before && after) return `${before}, ${joined}, ${after}`;
if (before) return `${before}, ${joined}`;
return `${joined}, ${after}`;
}

getTapFn(idx) {
Expand Down
Loading