index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. var micromatch = require('micromatch');
  3. var normalize = require('normalize-path');
  4. var path = require('path'); // required for tests.
  5. var arrify = function(a) { return a == null ? [] : (Array.isArray(a) ? a : [a]); };
  6. var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
  7. criteria = arrify(criteria);
  8. value = arrify(value);
  9. if (arguments.length === 1) {
  10. return anymatch.bind(null, criteria.map(function(criterion) {
  11. return typeof criterion === 'string' && criterion[0] !== '!' ?
  12. micromatch.matcher(criterion) : criterion;
  13. }));
  14. }
  15. startIndex = startIndex || 0;
  16. var string = value[0];
  17. var altString, altValue;
  18. var matched = false;
  19. var matchIndex = -1;
  20. function testCriteria(criterion, index) {
  21. var result;
  22. switch (Object.prototype.toString.call(criterion)) {
  23. case '[object String]':
  24. result = string === criterion || altString && altString === criterion;
  25. result = result || micromatch.isMatch(string, criterion);
  26. break;
  27. case '[object RegExp]':
  28. result = criterion.test(string) || altString && criterion.test(altString);
  29. break;
  30. case '[object Function]':
  31. result = criterion.apply(null, value);
  32. result = result || altValue && criterion.apply(null, altValue);
  33. break;
  34. default:
  35. result = false;
  36. }
  37. if (result) {
  38. matchIndex = index + startIndex;
  39. }
  40. return result;
  41. }
  42. var crit = criteria;
  43. var negGlobs = crit.reduce(function(arr, criterion, index) {
  44. if (typeof criterion === 'string' && criterion[0] === '!') {
  45. if (crit === criteria) {
  46. // make a copy before modifying
  47. crit = crit.slice();
  48. }
  49. crit[index] = null;
  50. arr.push(criterion.substr(1));
  51. }
  52. return arr;
  53. }, []);
  54. if (!negGlobs.length || !micromatch.any(string, negGlobs)) {
  55. if (path.sep === '\\' && typeof string === 'string') {
  56. altString = normalize(string);
  57. altString = altString === string ? null : altString;
  58. if (altString) altValue = [altString].concat(value.slice(1));
  59. }
  60. matched = crit.slice(startIndex, endIndex).some(testCriteria);
  61. }
  62. return returnIndex === true ? matchIndex : matched;
  63. };
  64. module.exports = anymatch;