Skip to content

Commit

Permalink
feat(matcher): allow regex string to be parsed as regex (#2324)
Browse files Browse the repository at this point in the history
* feat(matcher): allow regex string to be parsed as regex

* dont use startsWith

* fix
  • Loading branch information
straker authored Jun 25, 2020
1 parent a5409d4 commit 321b2d1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/commons/matches/from-primative.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* match.fromPrimative('foo', ['foo', 'bar']) // true, string is included
* match.fromPrimative('foo', /foo/) // true, string matches regex
* match.fromPrimative('foo', str => str.toUpperCase() === 'FOO') // true, function return is truthy
* match.fromPrimative('foo', '/foo/') // true, string matches regex string
* ```
*
* @private
Expand All @@ -24,6 +25,11 @@ function fromPrimative(someString, matcher) {
if (matcher instanceof RegExp) {
return matcher.test(someString);
}
// matcher starts and ends with "/"
if (/^\/.*\/$/.test(matcher)) {
const pattern = matcher.substring(1, matcher.length - 1);
return new RegExp(pattern).test(someString);
}
return matcher === someString;
}

Expand Down
9 changes: 9 additions & 0 deletions test/commons/matches/from-primative.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,13 @@ describe('matches.fromPrimative', function() {
assert.isFalse(fromPrimative('foobar', /^(foo|bar|baz)$/));
});
});

describe('with RegExp string', function() {
it('returns true if the regexp matches', function() {
assert.isTrue(fromPrimative('bar', '/^(foo|bar|baz)$/'));
});
it('returns false if the regexp does not match', function() {
assert.isFalse(fromPrimative('foobar', '/^(foo|bar|baz)$/'));
});
});
});

0 comments on commit 321b2d1

Please sign in to comment.