UNPKG

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