Skip to content

Commit

Permalink
Add atStart() and atEnd() convenience methods to MatchingContext.
Browse files Browse the repository at this point in the history
  • Loading branch information
martincizek committed Dec 4, 2019
1 parent 5ebf0d1 commit 8555ce6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/MatchingContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ class MatchingContext {
? mlen
: emptyMatchAdvance(this.match.input, index, this.replacer.regexp.unicode));
}

atStart() {
return this.match.index === 0;
}

atEnd() {
const { match } = this;
return match.index + match[0].length >= match.input.length;
}
}

export default MatchingContext;
26 changes: 26 additions & 0 deletions test/matching-context.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const UnionReplacer = require('../dist/union-replacer.cjs');

describe('MatchingContext', () => {
function startEndReplace(mctx) {
const l = mctx.match[0].length;
const s = mctx.atStart() ? 'S' : '_';
const e = mctx.atEnd() ? 'E' : '_';
return `[${s}${e}:${l}]`;
}
it('recognizes start and end', () => {
const r = new UnionReplacer([[/^x|y|z$/, startEndReplace, true]]);
expect(r.replace('xyz')).toBe('[S_:1][__:1][_E:1]');
});
it('recognizes start = end match and empty end', () => {
const r = new UnionReplacer([[/x|$/, startEndReplace, true]]);
expect(r.replace('x')).toBe('[SE:1][_E:0]');
});
it('recognizes empty start and empty end', () => {
const r = new UnionReplacer([[/^|$/, startEndReplace, true]]);
expect(r.replace('x')).toBe('[S_:0]x[_E:0]');
});
it('recognizes empty start and empty on empty string', () => {
const r = new UnionReplacer([[/^|$/, startEndReplace, true]]);
expect(r.replace('')).toBe('[SE:0]');
});
});

0 comments on commit 8555ce6

Please sign in to comment.