Skip to content

Commit

Permalink
feat: add clear() method to list and queue classes (#1011)
Browse files Browse the repository at this point in the history
Add an O(1) method to clear a list or queue of all items.
  • Loading branch information
johnnylam88 committed Sep 13, 2021
1 parent b0cdca5 commit c95f756
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/tools/Queue.ts
Expand Up @@ -89,6 +89,12 @@ export class Deque<T> {
return (this.length > 0 && this.buffer[this.last]) || undefined;
}

clear() {
this.first = 0;
this.last = 0;
this.length = 0;
}

indexAfter = (index: number) => {
return (index < this.capacity && index + 1) || 1;
};
Expand Down
9 changes: 8 additions & 1 deletion src/tools/list.spec.ts
Expand Up @@ -17,7 +17,7 @@ test("from empty array", () => {
expect(l.asArray()).toEqual({});
});

test("nodeOf from empety list", () => {
test("nodeOf from empty list", () => {
const l = new List<number>();
const [node, index] = l.nodeOf(10);
expect(node).toBe(undefined);
Expand Down Expand Up @@ -441,3 +441,10 @@ test("replace with front to back iterator of list", () => {
expect(iterator.next()).toBe(false);
expect(l.asArray()).toEqual({ 1: 10, 2: 40, 3: 30 });
});

test("cleared list is empty", () => {
const l = new List<number>();
l.fromArray({ 1: 10, 2: 20, 3: 30 });
l.clear();
expect(l.isEmpty()).toBe(true);
});
5 changes: 5 additions & 0 deletions src/tools/list.ts
Expand Up @@ -95,6 +95,11 @@ export class List<T> {
return (this.head && this.head.prev.value) || undefined;
}

clear() {
this.head = undefined;
this.length = 0;
}

backToFrontIterator(): Iterator<T> {
return new ListBackToFrontIterator<T>(this);
}
Expand Down
7 changes: 7 additions & 0 deletions src/tools/queue.spec.ts
Expand Up @@ -650,3 +650,10 @@ test("replace with front to back iterator of queue", () => {
expect(iterator.next()).toBe(false);
expect(q.asArray()).toEqual({ 1: 10, 2: 40, 3: 30 });
});

test("cleared queue is empty", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
q.clear();
expect(q.isEmpty()).toBe(true);
});

0 comments on commit c95f756

Please sign in to comment.