index.js 1.9 KB

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