Skip to content

Commit

Permalink
Fix Heap.forEach to just copy the array but keep the same references …
Browse files Browse the repository at this point in the history
…to the elements inside
  • Loading branch information
felipernb committed Aug 15, 2014
1 parent e794d88 commit f92635e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
6 changes: 5 additions & 1 deletion data_structures/heap.js
Expand Up @@ -90,7 +90,11 @@ MinHeap.prototype.heapify = function (a) {
};

MinHeap.prototype.forEach = function (fn) {
var elementsCopy = JSON.parse(JSON.stringify(this._elements));
var elementsCopy = [];

for (var i = 0; i < this._elements.length; i++) {
elementsCopy.push(this._elements[i]);
}

var element = this.extract();
while (typeof element !== 'undefined') {
Expand Down
3 changes: 3 additions & 0 deletions test/data_structures/heap.js
Expand Up @@ -65,6 +65,9 @@ describe('Min Heap', function () {
});

assert.deepEqual(output, [0, 1, 2, 3, 10, 1000]);

// Make sure nothing was really removed
assert.equal(h.n, 6);
});
});

Expand Down

0 comments on commit f92635e

Please sign in to comment.