2017-05-03 15:35:00 +02:00
|
|
|
'use strict';
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
var set = require('set-getter');
|
|
|
|
|
2017-05-03 15:35:00 +02:00
|
|
|
/**
|
|
|
|
* Cache results of the first function call to ensure only calling once.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* var utils = require('lazy-cache')(require);
|
|
|
|
* // cache the call to `require('ansi-yellow')`
|
|
|
|
* utils('ansi-yellow', 'yellow');
|
|
|
|
* // use `ansi-yellow`
|
|
|
|
* console.log(utils.yellow('this is yellow'));
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @param {Function} `fn` Function that will be called only once.
|
|
|
|
* @return {Function} Function that can be called to get the cached function
|
|
|
|
* @api public
|
|
|
|
*/
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
function lazyCache(requireFn) {
|
2017-05-03 15:35:00 +02:00
|
|
|
var cache = {};
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
return function proxy(name, alias) {
|
|
|
|
var key = alias;
|
2017-05-03 15:35:00 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
// camel-case the module `name` if `alias` is not defined
|
|
|
|
if (typeof key !== 'string') {
|
|
|
|
key = camelcase(name);
|
|
|
|
}
|
2017-05-03 15:35:00 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
// create a getter to lazily invoke the module the first time it's called
|
2017-05-03 15:35:00 +02:00
|
|
|
function getter() {
|
2017-08-14 05:01:11 +02:00
|
|
|
return cache[key] || (cache[key] = requireFn(name));
|
2017-05-03 15:35:00 +02:00
|
|
|
}
|
2017-08-14 05:01:11 +02:00
|
|
|
|
|
|
|
// trip the getter if `process.env.UNLAZY` is defined
|
|
|
|
if (unlazy(process.env)) {
|
|
|
|
getter();
|
|
|
|
}
|
|
|
|
|
|
|
|
set(proxy, key, getter);
|
2017-05-03 15:35:00 +02:00
|
|
|
return getter;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2017-08-14 05:01:11 +02:00
|
|
|
* Return true if `process.env.LAZY` is true, or travis is running.
|
|
|
|
*/
|
|
|
|
|
|
|
|
function unlazy(env) {
|
|
|
|
return env.UNLAZY === 'true' || env.UNLAZY === true || env.TRAVIS;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Camelcase the the given module `name`.
|
2017-05-03 15:35:00 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
function camelcase(str) {
|
|
|
|
if (str.length === 1) {
|
|
|
|
return str.toLowerCase();
|
|
|
|
}
|
|
|
|
str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
|
|
|
|
return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
|
|
|
|
return ch.toUpperCase();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Expose `lazyCache`
|
|
|
|
*/
|
|
|
|
|
|
|
|
module.exports = lazyCache;
|