Skip to content

Commit

Permalink
PR feedback.
Browse files Browse the repository at this point in the history
  • Loading branch information
kinyoklion committed Dec 12, 2024
1 parent 241598b commit 1247369
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,27 @@ it('when the buffer is exceeded it will wrap around', () => {

expect(buffer.toArray()).toEqual(expectedItems);
});

it('can reset the buffer', () => {
const bufferSize = 5;
const numberBuffers = 4;
const buffer = new RollingBuffer(bufferSize, numberBuffers);
const demoItems = Array.from(new Array(10), (_, i) => i);

demoItems.forEach(buffer.push.bind(buffer));
buffer.reset();

expect(buffer.toArray()).toEqual([]);
});

it('returns correct items when buffer is partially filled', () => {
const bufferSize = 5;
const numberBuffers = 4;
const buffer = new RollingBuffer(bufferSize, numberBuffers);
const itemsToAdd = 7; // Less than total capacity
const demoItems = Array.from(new Array(itemsToAdd), (_, i) => i);

demoItems.forEach(buffer.push.bind(buffer));

expect(buffer.toArray()).toEqual(demoItems);
});
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,20 @@ export default class RollingBuffer {

toArray(): any[] {
const asArray: any[] = [];
const size = this._buffers.reduce((acc: number, item: EventBuffer) => {
if (item.isPopulated()) {
return acc + 1;
}
return acc;
}, 0);

for (let index = this._headPointer; index < this._headPointer + size; index += 1) {
// Loop through the buffers, apprending their contents to asArray, until we find an empty one.
for (
let index = this._headPointer;
index < this._headPointer + this._buffers.length;
index += 1
) {
const realIndex = index % this._buffers.length;
asArray.push(...this._buffers[realIndex].content);
const item = this._buffers[realIndex];

if (!item.isPopulated) {
break;
}
asArray.push(...item.content);
}

return asArray;
Expand Down

0 comments on commit 1247369

Please sign in to comment.