index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* jshint node: true */
  2. 'use strict';
  3. /**
  4. # wildcard
  5. Very simple wildcard matching, which is designed to provide the same
  6. functionality that is found in the
  7. [eve](https://github.com/adobe-webplatform/eve) eventing library.
  8. ## Usage
  9. It works with strings:
  10. <<< examples/strings.js
  11. Arrays:
  12. <<< examples/arrays.js
  13. Objects (matching against keys):
  14. <<< examples/objects.js
  15. While the library works in Node, if you are are looking for file-based
  16. wildcard matching then you should have a look at:
  17. <https://github.com/isaacs/node-glob>
  18. **/
  19. function WildcardMatcher(text, separator) {
  20. this.text = text = text || '';
  21. this.hasWild = ~text.indexOf('*');
  22. this.separator = separator;
  23. this.parts = text.split(separator);
  24. }
  25. WildcardMatcher.prototype.match = function(input) {
  26. var matches = true;
  27. var parts = this.parts;
  28. var ii;
  29. var partsCount = parts.length;
  30. var testParts;
  31. if (typeof input == 'string' || input instanceof String) {
  32. if (!this.hasWild && this.text != input) {
  33. matches = false;
  34. } else {
  35. testParts = (input || '').split(this.separator);
  36. for (ii = 0; matches && ii < partsCount; ii++) {
  37. if (parts[ii] === '*') {
  38. continue;
  39. } else if (ii < testParts.length) {
  40. matches = parts[ii] === testParts[ii];
  41. } else {
  42. matches = false;
  43. }
  44. }
  45. // If matches, then return the component parts
  46. matches = matches && testParts;
  47. }
  48. }
  49. else if (typeof input.splice == 'function') {
  50. matches = [];
  51. for (ii = input.length; ii--; ) {
  52. if (this.match(input[ii])) {
  53. matches[matches.length] = input[ii];
  54. }
  55. }
  56. }
  57. else if (typeof input == 'object') {
  58. matches = {};
  59. for (var key in input) {
  60. if (this.match(key)) {
  61. matches[key] = input[key];
  62. }
  63. }
  64. }
  65. return matches;
  66. };
  67. module.exports = function(text, test, separator) {
  68. var matcher = new WildcardMatcher(text, separator || /[\/\.]/);
  69. if (typeof test != 'undefined') {
  70. return matcher.match(test);
  71. }
  72. return matcher;
  73. };