Lazy decoration (part 4, lazyMethod/lazyMethods) (#4144)

This commit is contained in:
Jaco
2021-11-02 07:35:32 +02:00
committed by GitHub
parent db2e97bf66
commit 9e7c0a1959
2 changed files with 30 additions and 0 deletions
+1
View File
@@ -5,5 +5,6 @@ export * from './createClass';
export * from './createType';
export * from './encodeTypes';
export * from './getTypeDef';
export * from './lazy';
export * from './registry';
export * from './typeSplit';
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
type WithToString = { toString: () => string };
export function lazyMethod <T, K> (result: Record<string, T>, item: K, creator: (d: K) => T, getName?: (d: K) => string): void {
let cached: T | null = null;
Object.defineProperty(result, getName ? getName(item) : (item as WithToString).toString(), {
enumerable: true,
get: (): T => {
if (!cached) {
cached = creator(item);
}
return cached;
}
});
}
export function lazyMethods <T, K> (items: K[], creator: (v: K) => T, getName?: (m: K) => string): Record<string, T> {
const result: Record<string, T> = {};
for (let i = 0; i < items.length; i++) {
lazyMethod(result, items[i], creator, getName);
}
return result;
}