Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 16006e0

Browse files
committed
fix: order of length check in remove()
1 parent 5338710 commit 16006e0

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

‎src/_DataStructures_/Heaps/MaxHeap/MaxHeap.test.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,16 @@ describe('MaxHeap', () => {
4747
expect(mh.remove()).toEqual(1);
4848
expect(mh.getMax()).toEqual(null);
4949
});
50+
51+
it('Should return `null` on `remove() called on empty heap`', () => {
52+
expect(mh.getMax()).toEqual(null);
53+
});
54+
55+
it('Should create MaxHeap using collection : [2, 12, 0, 90]', () => {
56+
const arr = [2, 12, 0, 90];
57+
const mHBulk = new MaxHeap(arr);
58+
59+
expect(mHBulk.getMax()).toEqual(90);
60+
// expect(mHBulk.()).toEqual(90);
61+
});
5062
});

‎src/_DataStructures_/Heaps/MaxHeap/index.js‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,13 @@ class MaxHeap {
1919
return this.heap[0] || null;
2020
}
2121

22-
// eslint-disable-next-line consistent-return
2322
remove() {
24-
// return the element at the root
2523
const max = this.heap[0] || null;
24+
// return the element at the root
25+
if (this.heap.length === 1) {
26+
this.heap.pop();
27+
}
28+
2629
if (this.heap.length > 1) {
2730
// move the leaf to the root
2831
this.heap[0] = this.heap[this.heap.length - 1];
@@ -31,11 +34,6 @@ class MaxHeap {
3134
// eslint-disable-next-line no-underscore-dangle
3235
this.__heapify(0);
3336
}
34-
35-
if (this.heap.length === 1) {
36-
this.heap.pop();
37-
}
38-
3937
return max;
4038
}
4139

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /