UNPKG

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