Lazy decoration (part 4, lazyMethod/lazyMethods) (#4144)
This commit is contained in:
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user