Skip to content

Commit

Permalink
Adjust flag d indices for emulation groups when using subclass
Browse files Browse the repository at this point in the history
  • Loading branch information
slevithan committed Nov 14, 2024
1 parent ff7adf5 commit c24084c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 7 additions & 0 deletions spec/regex-tag.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,13 @@ describe('regex', () => {
expect([...'ab'.matchAll(regex({flags: 'g', subclass: false})`(?>(?<a>.))(?<b>.)`)][0][2]).not.toBe('b');
expect('ab'.split(regex({subclass: false})`(?>(?<a>.))(?<b>.)`)).not.toEqual(['', 'a', 'b', '']);
});

it('should adjust indices with flag d for emulation groups', () => {
expect(regex({flags: 'd', subclass: true})`(?>.)`.exec('a').indices).toHaveSize(1);

// Documenting behavior when the option is not used
expect(regex({flags: 'd', subclass: false})`(?>.)`.exec('a').indices).toHaveSize(2);
});
});
});
});
14 changes: 11 additions & 3 deletions src/regex.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,20 @@ class WrappedRegExp extends RegExp {
if (!match || !this.#captureMap) {
return match;
}
const copy = [...match];
const matchCopy = [...match];
// Empty all but the first value of the array while preserving its other properties
match.length = 1;
for (let i = 1; i < copy.length; i++) {
let indicesCopy;
if (this.hasIndices) {
indicesCopy = [...match.indices];
match.indices.length = 1;
}
for (let i = 1; i < matchCopy.length; i++) {
if (this.#captureMap[i]) {
match.push(copy[i]);
match.push(matchCopy[i]);
if (this.hasIndices) {
match.indices.push(indicesCopy[i]);
}
}
}
return match;
Expand Down

0 comments on commit c24084c

Please sign in to comment.