4 * Cache results of the first function call to ensure only calling once.
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'));
14 * @param {Function} `fn` Function that will be called only once.
15 * @return {Function} Function that can be called to get the cached function
19 function lazyCache(fn) {
21 var proxy = function(mod, name) {
22 name = name || camelcase(mod);
24 // check both boolean and string in case `process.env` cases to string
25 if (process.env.UNLAZY === 'true' || process.env.UNLAZY === true || process.env.TRAVIS) {
26 cache[name] = fn(mod);
29 Object.defineProperty(proxy, name, {
36 if (cache.hasOwnProperty(name)) {
39 return (cache[name] = fn(mod));
47 * Used to camelcase the name to be stored on the `lazy` object.
49 * @param {String} `str` String containing `_`, `.`, `-` or whitespace that will be camelcased.
50 * @return {String} camelcased string.
53 function camelcase(str) {
54 if (str.length === 1) {
55 return str.toLowerCase();
57 str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
58 return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
59 return ch.toUpperCase();
67 module.exports = lazyCache;