-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
example.js
58 lines (47 loc) · 1.21 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'use strict';
var toPath = require('to-object-path');
var getter = require('./');
/**
* Normal getters on an object. Just returning strings.
*/
var obj = {};
// root level property
getter(obj, 'foo', function() {
return 'bar';
});
console.log(obj.foo);
// property dot notation
getter(obj, 'bar.baz', function() {
return 'qux';
});
console.log(obj.bar.baz);
// property array notation
getter(obj, ['beep', 'boop'], function() {
return 'bop';
});
console.log(obj.beep.boop);
/**
* Advanced getter that caches results to ensure work is only done once.
*/
var lazy = function(requireFn) {
var cache = {};
return function fn(name, alias) {
var key = toPath(alias || name);
return getter(fn, alias || name, function() {
return cache[key] || (cache[key] = requireFn(name));
});
};
};
var calls = {};
var utils = lazy(function(key) {
calls[key] = (calls[key] || 0) + 1;
return key.toUpperCase();
});
utils('foo');
utils('qux', 'bar.baz');
utils('bop', ['beep', 'boop']);
// show that the lazy getter function is only called once for each property.
console.log(utils.foo, utils.foo);
console.log(utils.bar.baz, utils.bar.baz);
console.log(utils.beep.boop, utils.beep.boop);
console.log(calls);