Skip to content

Commit 78b26d2

Browse files
authored
Allow .slice on Vec types (#3130)
* Allow .slice on Vec types * Apply suggestions from code review * Update packages/types/src/codec/AbstractArray.ts
1 parent e4d5be8 commit 78b26d2

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

packages/types/src/codec/AbstractArray.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,4 +159,11 @@ export abstract class AbstractArray<T extends Codec> extends Array<T> implements
159159
public includes (check: unknown): boolean {
160160
return this.some((value: T) => value.eq(check));
161161
}
162+
163+
/**
164+
* @description Returns a slice of an array
165+
*/
166+
public slice (start?: number, end?: number): T[] {
167+
return this.toArray().slice(start, end);
168+
}
162169
}

packages/types/src/codec/Vec.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { Codec, CodecTo } from '../types';
66

77
import { Metadata } from '@polkadot/metadata';
88
import rpcMetadata from '@polkadot/metadata/static';
9+
import { randomAsU8a } from '@polkadot/util-crypto';
910

1011
import { createTypeUnsafe, TypeRegistry } from '../create';
1112
import { GenericAccountId as AccountId } from '../generic';
@@ -170,5 +171,14 @@ describe('Vec', (): void => {
170171

171172
expect(vec.indexOf(myId)).toEqual(2);
172173
});
174+
175+
it('allows a slice operator', (): void => {
176+
const vec = registry.createType('Vec<AccountId>', [
177+
randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a(), randomAsU8a()
178+
]);
179+
180+
expect(vec).toHaveLength(10);
181+
expect(vec.slice(2, 7)).toHaveLength(5);
182+
});
173183
});
174184
});

0 commit comments

Comments
 (0)