Нема описа

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. /**
  3. * Cache results of the first function call to ensure only calling once.
  4. *
  5. * ```js
  6. * var utils = require('lazy-cache')(require);
  7. * // cache the call to `require('ansi-yellow')`
  8. * utils('ansi-yellow', 'yellow');
  9. * // use `ansi-yellow`
  10. * console.log(utils.yellow('this is yellow'));
  11. * ```
  12. *
  13. * @param {Function} `fn` Function that will be called only once.
  14. * @return {Function} Function that can be called to get the cached function
  15. * @api public
  16. */
  17. function lazyCache(fn) {
  18. var cache = {};
  19. var proxy = function(mod, name) {
  20. name = name || camelcase(mod);
  21. // check both boolean and string in case `process.env` cases to string
  22. if (process.env.UNLAZY === 'true' || process.env.UNLAZY === true || process.env.TRAVIS) {
  23. cache[name] = fn(mod);
  24. }
  25. Object.defineProperty(proxy, name, {
  26. enumerable: true,
  27. configurable: true,
  28. get: getter
  29. });
  30. function getter() {
  31. if (cache.hasOwnProperty(name)) {
  32. return cache[name];
  33. }
  34. return (cache[name] = fn(mod));
  35. }
  36. return getter;
  37. };
  38. return proxy;
  39. }
  40. /**
  41. * Used to camelcase the name to be stored on the `lazy` object.
  42. *
  43. * @param {String} `str` String containing `_`, `.`, `-` or whitespace that will be camelcased.
  44. * @return {String} camelcased string.
  45. */
  46. function camelcase(str) {
  47. if (str.length === 1) {
  48. return str.toLowerCase();
  49. }
  50. str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
  51. return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
  52. return ch.toUpperCase();
  53. });
  54. }
  55. /**
  56. * Expose `lazyCache`
  57. */
  58. module.exports = lazyCache;