Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const escapeStringRegexp = require('escape-string-regexp');
  3. const regexpCache = new Map();
  4. function makeRegexp(pattern, options) {
  5. options = {
  6. caseSensitive: false,
  7. ...options
  8. };
  9. const cacheKey = pattern + JSON.stringify(options);
  10. if (regexpCache.has(cacheKey)) {
  11. return regexpCache.get(cacheKey);
  12. }
  13. const negated = pattern[0] === '!';
  14. if (negated) {
  15. pattern = pattern.slice(1);
  16. }
  17. pattern = escapeStringRegexp(pattern).replace(/\\\*/g, '[\\s\\S]*');
  18. const regexp = new RegExp(`^${pattern}$`, options.caseSensitive ? '' : 'i');
  19. regexp.negated = negated;
  20. regexpCache.set(cacheKey, regexp);
  21. return regexp;
  22. }
  23. module.exports = (inputs, patterns, options) => {
  24. if (!(Array.isArray(inputs) && Array.isArray(patterns))) {
  25. throw new TypeError(`Expected two arrays, got ${typeof inputs} ${typeof patterns}`);
  26. }
  27. if (patterns.length === 0) {
  28. return inputs;
  29. }
  30. const isFirstPatternNegated = patterns[0][0] === '!';
  31. patterns = patterns.map(pattern => makeRegexp(pattern, options));
  32. const result = [];
  33. for (const input of inputs) {
  34. // If first pattern is negated we include everything to match user expectation.
  35. let matches = isFirstPatternNegated;
  36. for (const pattern of patterns) {
  37. if (pattern.test(input)) {
  38. matches = !pattern.negated;
  39. }
  40. }
  41. if (matches) {
  42. result.push(input);
  43. }
  44. }
  45. return result;
  46. };
  47. module.exports.isMatch = (input, pattern, options) => {
  48. const inputArray = Array.isArray(input) ? input : [input];
  49. const patternArray = Array.isArray(pattern) ? pattern : [pattern];
  50. return inputArray.some(input => {
  51. return patternArray.every(pattern => {
  52. const regexp = makeRegexp(pattern, options);
  53. const matches = regexp.test(input);
  54. return regexp.negated ? !matches : matches;
  55. });
  56. });
  57. };