mirror of
https://github.com/brendan-ch/project-inter-server.git
synced 2026-04-17 07:50:31 +00:00
Optimize the append method to check if the data is already sorted
This commit is contained in:
@@ -38,6 +38,9 @@ export class CircularQueue<T> {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastItem = this.get(this._size - 1);
|
||||
const isAlreadyInOrder = lastItem && sortingCallback(lastItem, data) <= 0;
|
||||
|
||||
if (this._size < this._capacity) {
|
||||
this.endIndex = (this.endIndex + 1) % this._capacity;
|
||||
this._data[this.endIndex] = data;
|
||||
@@ -48,8 +51,10 @@ export class CircularQueue<T> {
|
||||
this._data[this.endIndex] = data;
|
||||
}
|
||||
|
||||
if (!isAlreadyInOrder) {
|
||||
this.sortData(sortingCallback);
|
||||
}
|
||||
}
|
||||
|
||||
popFront = () => {
|
||||
if (this._size === 0) {
|
||||
|
||||
@@ -69,6 +69,31 @@ describe("CircularQueue", () => {
|
||||
expect(queue.size()).toBe(1);
|
||||
expect(queue.get(0)).toEqual(testItems.test);
|
||||
});
|
||||
|
||||
it("optimizes append when items are already in order", () => {
|
||||
const queue = new CircularQueue<TestItem>(5);
|
||||
let sortCallCount = 0;
|
||||
|
||||
const trackingSortCallback = (a: TestItem, b: TestItem) => {
|
||||
sortCallCount++;
|
||||
return a.id - b.id;
|
||||
};
|
||||
|
||||
queue.appendWithSorting(testItems.first, trackingSortCallback);
|
||||
expect(sortCallCount).toBe(0);
|
||||
|
||||
queue.appendWithSorting(testItems.second, trackingSortCallback);
|
||||
expect(sortCallCount).toBe(1);
|
||||
|
||||
queue.appendWithSorting(testItems.third, trackingSortCallback);
|
||||
expect(sortCallCount).toBe(2);
|
||||
|
||||
queue.appendWithSorting({ id: 0, value: "zero" }, trackingSortCallback);
|
||||
expect(sortCallCount).toBeGreaterThan(3);
|
||||
|
||||
expect(queue.get(0)).toEqual({ id: 0, value: "zero" });
|
||||
expect(queue.get(1)).toEqual(testItems.first);
|
||||
});
|
||||
});
|
||||
|
||||
describe("popFront", () => {
|
||||
|
||||
Reference in New Issue
Block a user