Mirror: The magical sticky regex-based parser generator 🧙

Add predicate support to interpolations

+19 -11
+7 -4
src/core.js
··· 33 33 return match; 34 34 }; 35 35 36 - export const interpolation = (state) => { 36 + export const interpolation = (predicate) => (state) => { 37 37 let match; 38 38 39 - const input = state.quasis[state.x]; 40 - if (!input || state.y >= input.length) { 39 + if ( 40 + state.y >= state.quasis[state.x].length && 41 + state.x < state.expressions.length 42 + ) { 41 43 state.y = 0; 42 - match = state.expressions[state.x++] || match; 44 + match = state.expressions[state.x++]; 45 + if (predicate && match) match = predicate(match); 43 46 } 44 47 45 48 return match;
+12 -7
src/core.test.js
··· 556 556 describe('interpolation parsing', () => { 557 557 const node = match('node')` 558 558 ${/1/} 559 - ${interpolation} 559 + ${interpolation((x) => x > 1 && x)} 560 560 ${/3/} 561 561 `; 562 562 563 - const expected = ['1', 2, '3']; 564 - expected.tag = 'node'; 563 + it('matches interpolations', () => { 564 + const expected = ['1', 2, '3']; 565 + expected.tag = 'node'; 566 + expect(parse(node)`1${2}3`).toEqual(expected); 567 + }); 565 568 566 - expect(parse(node)`1${2}3`).toEqual(expected); 567 - expect(parse(node)`13`).toBe(undefined); 568 - expect(parse(node)`13${2}`).toBe(undefined); 569 - expect(parse(node)`${2}13`).toBe(undefined); 569 + it('does not match invalid inputs', () => { 570 + expect(parse(node)`13`).toBe(undefined); 571 + expect(parse(node)`13${2}`).toBe(undefined); 572 + expect(parse(node)`${2}13`).toBe(undefined); 573 + expect(parse(node)`1${1}3`).toBe(undefined); 574 + }); 570 575 });