Allow .slice on Vec types (#3130)

* Allow .slice on Vec types

* Apply suggestions from code review

* Update packages/types/src/codec/AbstractArray.ts
This commit is contained in:
Jaco Greeff
2021-01-31 12:48:05 +01:00
committed by GitHub
parent e4d5be85f6
commit 78b26d2d40
2 changed files with 17 additions and 0 deletions
@@ -159,4 +159,11 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
public includes (check: unknown): boolean {
return this.some((value: T) => value.eq(check));
}
/**
* @description Returns a slice of an array
*/
public slice (start?: number, end?: number): T[] {
return this.toArray().slice(start, end);
}
}
+10
View File
@@ -6,6 +6,7 @@ import type { Codec, CodecTo } from '../types';
import { Metadata } from '@polkadot/metadata';
import rpcMetadata from '@polkadot/metadata/static';
import { randomAsU8a } from '@polkadot/util-crypto';
import { createTypeUnsafe, TypeRegistry } from '../create';
import { GenericAccountId as AccountId } from '../generic';
@@ -170,5 +171,14 @@ describe('Vec', (): void => {
expect(vec.indexOf(myId)).toEqual(2);
});
it('allows a slice operator', (): void => {
const vec = registry.createType('Vec<AccountId>', [
randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a()
]);
expect(vec).toHaveLength(10);
expect(vec.slice(2, 7)).toHaveLength(5);
});
});
});