Skip to content

Commit 7a7b7c2

Browse files
committed
feat: create DynamicBuffer with initial data.
1 parent 9949e1a commit 7a7b7c2

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/dynamicBuffer.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,25 @@ export class DynamicBuffer {
7676

7777
private factor: number;
7878

79-
constructor(options?: DynamicBufferOptions) {
79+
constructor();
80+
81+
constructor(options: DynamicBufferOptions);
82+
83+
constructor(data: string);
84+
85+
constructor(data: string, options: DynamicBufferOptions);
86+
87+
constructor(
88+
data?: string | DynamicBufferOptions,
89+
options?: DynamicBufferOptions,
90+
) {
91+
if (typeof data !== 'string') {
92+
// eslint-disable-next-line no-param-reassign
93+
options = data;
94+
// eslint-disable-next-line no-param-reassign
95+
data = undefined;
96+
}
97+
8098
if (options?.size !== undefined) {
8199
this.size = options.size;
82100
} else {
@@ -99,6 +117,10 @@ export class DynamicBuffer {
99117
if (this.size > 0) {
100118
this.buffer = Buffer.alloc(this.size, this.fill, this.encoding);
101119
}
120+
121+
if (data) {
122+
this.append(data);
123+
}
102124
}
103125

104126
/**

test/dynamicBuffer.spec.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,21 @@ describe('Initialization tests', () => {
3131
assert.throws(() => new DynamicBuffer({ size: constants.MAX_LENGTH + 1 }));
3232
});
3333

34-
it("Test initializing with invalid factor", () => {
34+
it('Test initializing with invalid factor', () => {
3535
assert.throws(() => {
36+
// eslint-disable-next-line no-new
3637
new DynamicBuffer({
3738
factor: -1,
3839
});
3940
});
4041
});
42+
43+
it('Test initializing with initial data', () => {
44+
const data = 'Hello world';
45+
const buffer = new DynamicBuffer(data);
46+
47+
assert.equal(buffer.toString(), data);
48+
});
4149
});
4250

4351
describe('Resize tests', () => {

0 commit comments

Comments
 (0)