2017-05-28 00:38:50 +02:00
|
|
|
'use strict';
|
2017-08-14 05:01:11 +02:00
|
|
|
const escapeStringRegexp = require('escape-string-regexp');
|
|
|
|
|
|
|
|
const reCache = new Map();
|
2017-05-28 00:38:50 +02:00
|
|
|
|
|
|
|
function makeRe(pattern, shouldNegate) {
|
2017-08-14 05:01:11 +02:00
|
|
|
const cacheKey = pattern + shouldNegate;
|
2017-05-28 00:38:50 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
if (reCache.has(cacheKey)) {
|
|
|
|
return reCache.get(cacheKey);
|
2017-05-28 00:38:50 +02:00
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
let negated = false;
|
2017-05-28 00:38:50 +02:00
|
|
|
|
|
|
|
if (pattern[0] === '!') {
|
|
|
|
negated = true;
|
|
|
|
pattern = pattern.slice(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
pattern = escapeStringRegexp(pattern).replace(/\\\*/g, '.*');
|
|
|
|
|
|
|
|
if (negated && shouldNegate) {
|
2017-08-14 05:01:11 +02:00
|
|
|
pattern = `(?!${pattern})`;
|
2017-05-28 00:38:50 +02:00
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
const re = new RegExp(`^${pattern}$`, 'i');
|
2017-05-28 00:38:50 +02:00
|
|
|
re.negated = negated;
|
2017-08-14 05:01:11 +02:00
|
|
|
reCache.set(cacheKey, re);
|
2017-05-28 00:38:50 +02:00
|
|
|
|
|
|
|
return re;
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
module.exports = (inputs, patterns) => {
|
2017-05-28 00:38:50 +02:00
|
|
|
if (!(Array.isArray(inputs) && Array.isArray(patterns))) {
|
2017-08-14 05:01:11 +02:00
|
|
|
throw new TypeError(`Expected two arrays, got ${typeof inputs} ${typeof patterns}`);
|
2017-05-28 00:38:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (patterns.length === 0) {
|
|
|
|
return inputs;
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
const firstNegated = patterns[0][0] === '!';
|
2017-05-28 00:38:50 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
patterns = patterns.map(x => makeRe(x, false));
|
2017-05-28 00:38:50 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
const ret = [];
|
2017-05-28 00:38:50 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
for (const input of inputs) {
|
|
|
|
// If first pattern is negated we include everything to match user expectation
|
|
|
|
let matches = firstNegated;
|
2017-05-28 00:38:50 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
// TODO: Figure out why tests fail when I use a for-of loop here
|
|
|
|
for (let j = 0; j < patterns.length; j++) {
|
|
|
|
if (patterns[j].test(input)) {
|
2017-05-28 00:38:50 +02:00
|
|
|
matches = !patterns[j].negated;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (matches) {
|
2017-08-14 05:01:11 +02:00
|
|
|
ret.push(input);
|
2017-05-28 00:38:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
};
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
module.exports.isMatch = (input, pattern) => makeRe(pattern, true).test(input);
|