forked from gajus/surgeon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatchSubroutine.js
47 lines (36 loc) · 1.09 KB
/
matchSubroutine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// @flow
import parseRegex from 'regex-parser';
import {
vsprintf,
} from 'sprintf-js';
import {
SurgeonError,
} from '../errors';
import {
InvalidValueSentinel,
} from '../sentinels';
import Logger from '../Logger';
const log = Logger.child({
namespace: 'subroutine:match',
});
const matchSubroutine = (subject: string, [userRule, sprintfFormat]: $ReadOnlyArray<string>) => {
const rule: RegExp = parseRegex(userRule);
if (typeof subject !== 'string') {
throw new SurgeonError('Input is not a string.');
}
const matches = subject.match(rule);
if (!matches) {
log.debug({
input: subject,
}, 'input');
return new InvalidValueSentinel('Input does not match "' + rule.toString() + '" regular expression.');
}
if (matches.length === 1) {
throw new SurgeonError('Regular expression must define at least one capturing group.');
}
if (matches.length > 2 && !sprintfFormat) {
throw new SurgeonError('Must define sprintf template when matching multiple groups.');
}
return vsprintf(sprintfFormat || '%s', matches.slice(1));
};
export default matchSubroutine;