index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*!
  2. * regex-cache <https://github.com/jonschlinkert/regex-cache>
  3. *
  4. * Copyright (c) 2015-2017, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. 'use strict';
  8. var equal = require('is-equal-shallow');
  9. var basic = {};
  10. var cache = {};
  11. /**
  12. * Expose `regexCache`
  13. */
  14. module.exports = regexCache;
  15. /**
  16. * Memoize the results of a call to the new RegExp constructor.
  17. *
  18. * @param {Function} fn [description]
  19. * @param {String} str [description]
  20. * @param {Options} options [description]
  21. * @param {Boolean} nocompare [description]
  22. * @return {RegExp}
  23. */
  24. function regexCache(fn, str, opts) {
  25. var key = '_default_', regex, cached;
  26. if (!str && !opts) {
  27. if (typeof fn !== 'function') {
  28. return fn;
  29. }
  30. return basic[key] || (basic[key] = fn(str));
  31. }
  32. var isString = typeof str === 'string';
  33. if (isString) {
  34. if (!opts) {
  35. return basic[str] || (basic[str] = fn(str));
  36. }
  37. key = str;
  38. } else {
  39. opts = str;
  40. }
  41. cached = cache[key];
  42. if (cached && equal(cached.opts, opts)) {
  43. return cached.regex;
  44. }
  45. memo(key, opts, (regex = fn(str, opts)));
  46. return regex;
  47. }
  48. function memo(key, opts, regex) {
  49. cache[key] = {regex: regex, opts: opts};
  50. }
  51. /**
  52. * Expose `cache`
  53. */
  54. module.exports.cache = cache;
  55. module.exports.basic = basic;