UNPKG

2.3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.lazyMethods = exports.lazyMethod = void 0;
4/**
5 * @name lazyMethod
6 * @description
7 * Creates a lazy, on-demand getter for the specific value. Upon get the value will be evaluated.
8 */
9function lazyMethod(result, item, creator, getName, index = 0) {
10 const name = getName
11 ? getName(item, index)
12 : item.toString();
13 let value;
14 Object.defineProperty(result, name, {
15 // This allows for re-configuration with the embedded defineProperty below
16 // and ensures that on tested browsers and Node, it _will_ be redefined
17 // and thus short-circuited for future access
18 configurable: true,
19 enumerable: true,
20 // Use a function here, we don't want to capture the outer this, i.e.
21 // don't use arrow functions in this context since we have a this inside
22 get: function () {
23 // This check should _always_ be false and unneeded, since we override
24 // with a value below ... however we ensure we are quire vigilant against
25 // all environment failures, so we are rather be safe than sorry
26 if (value === undefined) {
27 value = creator(item, index, this);
28 try {
29 // re-define the property as a value, next time around this
30 // getter will only return the computed value
31 Object.defineProperty(this, name, { value });
32 }
33 catch {
34 // ignore any errors, since this _should_ not happen due to
35 // the "configurable" property above. But if it ever does
36 // from here-on we will be the cached value the next time
37 // around (with a very slight dip in performance)
38 }
39 }
40 return value;
41 }
42 });
43}
44exports.lazyMethod = lazyMethod;
45/**
46 * @name lazyMethods
47 * @description
48 * Creates lazy, on-demand getters for the specific values.
49 */
50function lazyMethods(result, items, creator, getName) {
51 for (let i = 0, count = items.length; i < count; i++) {
52 lazyMethod(result, items[i], creator, getName, i);
53 }
54 return result;
55}
56exports.lazyMethods = lazyMethods;