Skip to content

Commit b88a886

Browse files
committed
feat: add copyWithin method.
1 parent 7dcd5e7 commit b88a886

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/dynamicBuffer.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,26 @@ export class DynamicBuffer {
376376
return this.buffer.copy(target, targetStart, sourceStart, sourceEnd);
377377
}
378378

379+
/**
380+
* Returns the this buffer after copying a section of the buffer identified by start and end
381+
* to the same buffer starting at position target.
382+
*
383+
* @param target If target is negative, it is treated as length+target where length is the
384+
* length of the array.
385+
* @param start If start is negative, it is treated as length+start. If end is negative, it
386+
* is treated as length+end.
387+
* @param end If not specified, length of the this object is used as its default value.
388+
*/
389+
copyWithin(target: number, start: number, end: number = this.length): DynamicBuffer {
390+
if (!this.buffer || this.length === 0) {
391+
return this;
392+
}
393+
394+
this.buffer.subarray(0, this.length).copyWithin(target, start, end);
395+
396+
return this;
397+
}
398+
379399
/**
380400
* Creates and returns an iterator of key(index) and value(byte) pairs from this buffer.
381401
*

test/array.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,21 @@ import { describe, it } from 'mocha';
33

44
import { DynamicBuffer } from '../src';
55

6+
describe('CopyWithin tests', () => {
7+
it('Test copyWithin', () => {
8+
const buf = new DynamicBuffer('abcde');
9+
10+
assert.equal(buf.copyWithin(0, 3, 4).toString(), 'dbcde');
11+
assert.equal(buf.copyWithin(1, 3).toString(), 'ddede');
12+
});
13+
14+
it('Test copyWithin of empty buffer', () => {
15+
const buf = new DynamicBuffer();
16+
17+
assert.equal(buf.copyWithin(0, 3, 4).toString(), '');
18+
});
19+
});
20+
621
describe('Every tests', () => {
722
it('Test every', () => {
823
const buf1 = new DynamicBuffer('hello');

0 commit comments

Comments
 (0)