Skip to content

Commit

Permalink
feat: Introduce matchAll in fp
Browse files Browse the repository at this point in the history
  • Loading branch information
Iku-turso committed Jan 15, 2023
1 parent 1f212c0 commit 000b23e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/fp/src/matchAll/matchAll.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { isEmpty } from 'lodash/fp';

export default (targetString, regExpString) => {
const regExp = new RegExp(regExpString, 'g');

let matches = [];

let execMatch;
while ((execMatch = regExp.exec(targetString))) {
const [match, group = null] = execMatch;

matches.push({ match, group });
}

return !isEmpty(matches) ? matches : null;
};
38 changes: 38 additions & 0 deletions packages/fp/src/matchAll/matchAll.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import matchAll from './matchAll';

describe('matchAll', () => {
it('when called with regular expression containing multiple capturing groups and string that is matching, returns matches', () => {
const actual = matchAll(
'some-string-{containing}-some-{things-to-be-matched}',
/{([^}]*)}/,
);

expect(actual).toEqual([
{ match: '{containing}', group: 'containing' },
{ match: '{things-to-be-matched}', group: 'things-to-be-matched' },
]);
});

it('when called with regular expression containing single capturing group and string that is matching, returns matches', () => {
const actual = matchAll('some-string-{containing}', /{([^}]*)}/);

expect(actual).toEqual([{ match: '{containing}', group: 'containing' }]);
});

it('when called with regular expression with no capturing group and string that is matching, returns matches', () => {
const actual = matchAll('some', /./);

expect(actual).toEqual([
{ match: 's', group: null },
{ match: 'o', group: null },
{ match: 'm', group: null },
{ match: 'e', group: null },
]);
});

it('when called with regular expression and string that is not matching, returns null', () => {
const actual = matchAll('irrelevant', /{([^}]*)}/);

expect(actual).toBe(null);
});
});

0 comments on commit 000b23e

Please sign in to comment.