Skip to content

Commit ee8a0e2

Browse files
committed
feat: add reverse method.
1 parent 81e8198 commit ee8a0e2

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/dynamicBuffer.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,30 @@ export class DynamicBuffer {
691691
return this.compare(otherBuffer, 0, otherBuffer.length, 0, this.length) === 0;
692692
}
693693

694+
/**
695+
* Reverses the buffer in place and returns the reference to the buffer. The first byte in the
696+
* buffer now becoming the last, and the last byte in the buffer becoming the first.
697+
*
698+
* ```js
699+
* const buf = new DynamicBuffer('ABC');
700+
* console.log(buf.reverse().toString());
701+
* // CBA
702+
* console.log(buf.toString());
703+
* // CBA
704+
* ```
705+
*
706+
* @returns The reference to this buffer.
707+
*/
708+
reverse(): DynamicBuffer {
709+
if (!this.buffer || this.length === 0) {
710+
return this;
711+
}
712+
713+
this.buffer.subarray(0, this.length).reverse();
714+
715+
return this;
716+
}
717+
694718
/**
695719
* Write data into internal buffer with the specified offset.
696720
*

test/array.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import assert from 'assert';
2+
import { describe, it } from 'mocha';
3+
4+
import { DynamicBuffer } from '../src';
5+
6+
describe('Reverse tests', () => {
7+
it('Reverse buffer', () => {
8+
const buf = new DynamicBuffer('hello');
9+
const ref = buf.reverse();
10+
11+
assert.equal(buf.toString(), 'olleh');
12+
assert.equal(ref.toString(), 'olleh');
13+
});
14+
15+
it('Reverse empty buffer', () => {
16+
const buf = new DynamicBuffer();
17+
const ref = buf.reverse();
18+
19+
assert.equal(buf.toString(), '');
20+
assert.equal(ref.toString(), '');
21+
});
22+
});

0 commit comments

Comments
 (0)