index.js 1.3 KB

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