Optimize accountId -> accountIndex lookups (#2389)

This commit is contained in:
Jaco Greeff
2020-06-23 20:25:58 +02:00
committed by GitHub
parent f428a58006
commit bf472fdcf4
2 changed files with 22 additions and 7 deletions
+18 -7
View File
@@ -5,12 +5,14 @@
import { AccountId, AccountIndex } from '@polkadot/types/interfaces';
import { AccountIndexes } from '../types';
import { Observable } from 'rxjs';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiInterfaceRx } from '@polkadot/api/types';
import { memo } from '../util';
const cached = new Map<string, AccountIndex>();
/**
* @name idToIndex
* @param {( AccountId | string )} accountId - An accounts Id in different formats.
@@ -26,10 +28,19 @@ import { memo } from '../util';
* ```
*/
export function idToIndex (api: ApiInterfaceRx): (accountId: AccountId | string) => Observable<AccountIndex | undefined> {
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> =>
api.derive.accounts.indexes().pipe(
map((indexes: AccountIndexes): AccountIndex | undefined =>
(indexes || {})[accountId.toString()]
)
));
return memo((accountId: AccountId | string): Observable<AccountIndex | undefined> => {
const address = accountId.toString();
if (cached.has(address)) {
return of(cached.get(address));
}
return api.derive.accounts.indexes().pipe(
map((indexes: AccountIndexes): AccountIndex | undefined => {
Object.entries(indexes).forEach(([address, index]) => cached.set(address, index));
return cached.get(address);
})
);
});
}