您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

utils.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. var regex = require('regex-not');
  3. var Cache = require('fragment-cache');
  4. /**
  5. * Utils
  6. */
  7. var utils = module.exports;
  8. var cache = utils.cache = new Cache();
  9. /**
  10. * Cast `val` to an array
  11. * @return {Array}
  12. */
  13. utils.arrayify = function(val) {
  14. if (!Array.isArray(val)) {
  15. return [val];
  16. }
  17. return val;
  18. };
  19. /**
  20. * Memoize a generated regex or function
  21. */
  22. utils.memoize = function(type, pattern, options, fn) {
  23. var key = utils.createKey(type + pattern, options);
  24. if (cache.has(type, key)) {
  25. return cache.get(type, key);
  26. }
  27. var val = fn(pattern, options);
  28. if (options && options.cache === false) {
  29. return val;
  30. }
  31. cache.set(type, key, val);
  32. return val;
  33. };
  34. /**
  35. * Create the key to use for memoization. The key is generated
  36. * by iterating over the options and concatenating key-value pairs
  37. * to the pattern string.
  38. */
  39. utils.createKey = function(pattern, options) {
  40. var key = pattern;
  41. if (typeof options === 'undefined') {
  42. return key;
  43. }
  44. for (var prop in options) {
  45. key += ';' + prop + '=' + String(options[prop]);
  46. }
  47. return key;
  48. };
  49. /**
  50. * Create the regex to use for matching text
  51. */
  52. utils.createRegex = function(str) {
  53. var opts = {contains: true, strictClose: false};
  54. return regex(str, opts);
  55. };