UNPKG

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