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