index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. var set = require('set-getter');
  3. /**
  4. * Cache results of the first function call to ensure only calling once.
  5. *
  6. * ```js
  7. * var utils = require('lazy-cache')(require);
  8. * // cache the call to `require('ansi-yellow')`
  9. * utils('ansi-yellow', 'yellow');
  10. * // use `ansi-yellow`
  11. * console.log(utils.yellow('this is yellow'));
  12. * ```
  13. *
  14. * @param {Function} `fn` Function that will be called only once.
  15. * @return {Function} Function that can be called to get the cached function
  16. * @api public
  17. */
  18. function lazyCache(requireFn) {
  19. var cache = {};
  20. return function proxy(name, alias) {
  21. var key = alias;
  22. // camel-case the module `name` if `alias` is not defined
  23. if (typeof key !== 'string') {
  24. key = camelcase(name);
  25. }
  26. // create a getter to lazily invoke the module the first time it's called
  27. function getter() {
  28. return cache[key] || (cache[key] = requireFn(name));
  29. }
  30. // trip the getter if `process.env.UNLAZY` is defined
  31. if (unlazy(process.env)) {
  32. getter();
  33. }
  34. set(proxy, key, getter);
  35. return getter;
  36. };
  37. }
  38. /**
  39. * Return true if `process.env.LAZY` is true, or travis is running.
  40. */
  41. function unlazy(env) {
  42. return env.UNLAZY === 'true' || env.UNLAZY === true || env.TRAVIS;
  43. }
  44. /**
  45. * Camelcase the the given module `name`.
  46. */
  47. function camelcase(str) {
  48. if (str.length === 1) {
  49. return str.toLowerCase();
  50. }
  51. str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
  52. return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
  53. return ch.toUpperCase();
  54. });
  55. }
  56. /**
  57. * Expose `lazyCache`
  58. */
  59. module.exports = lazyCache;