Mirror: The magical sticky regex-based parser generator 🧙

Add predicate support to interpolations

Changed files
+19 -11
src
+7 -4
src/core.js
···
return match;
};
-
export const interpolation = (state) => {
let match;
-
const input = state.quasis[state.x];
-
if (!input || state.y >= input.length) {
state.y = 0;
-
match = state.expressions[state.x++] || match;
}
return match;
···
return match;
};
+
export const interpolation = (predicate) => (state) => {
let match;
+
if (
+
state.y >= state.quasis[state.x].length &&
+
state.x < state.expressions.length
+
) {
state.y = 0;
+
match = state.expressions[state.x++];
+
if (predicate && match) match = predicate(match);
}
return match;
+12 -7
src/core.test.js
···
describe('interpolation parsing', () => {
const node = match('node')`
${/1/}
-
${interpolation}
${/3/}
`;
-
const expected = ['1', 2, '3'];
-
expected.tag = 'node';
-
expect(parse(node)`1${2}3`).toEqual(expected);
-
expect(parse(node)`13`).toBe(undefined);
-
expect(parse(node)`13${2}`).toBe(undefined);
-
expect(parse(node)`${2}13`).toBe(undefined);
});
···
describe('interpolation parsing', () => {
const node = match('node')`
${/1/}
+
${interpolation((x) => x > 1 && x)}
${/3/}
`;
+
it('matches interpolations', () => {
+
const expected = ['1', 2, '3'];
+
expected.tag = 'node';
+
expect(parse(node)`1${2}3`).toEqual(expected);
+
});
+
it('does not match invalid inputs', () => {
+
expect(parse(node)`13`).toBe(undefined);
+
expect(parse(node)`13${2}`).toBe(undefined);
+
expect(parse(node)`${2}13`).toBe(undefined);
+
expect(parse(node)`1${1}3`).toBe(undefined);
+
});
});