From f92635eceed01618636b8fcd31760f7bc40ec67e Mon Sep 17 00:00:00 2001 From: Felipe Ribeiro Date: Fri, 15 Aug 2014 07:59:22 +0200 Subject: [PATCH] Fix Heap.forEach to just copy the array but keep the same references to the elements inside --- data_structures/heap.js | 6 +++++- test/data_structures/heap.js | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/data_structures/heap.js b/data_structures/heap.js index d5969ef..27402d0 100644 --- a/data_structures/heap.js +++ b/data_structures/heap.js @@ -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') { diff --git a/test/data_structures/heap.js b/test/data_structures/heap.js index ac8ba9c..fbeb175 100644 --- a/test/data_structures/heap.js +++ b/test/data_structures/heap.js @@ -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); }); });