Min Heap Implementation












0














Min Heap Implementation



As an exercise, I wanted to implement a min heap using JavaScript.



I'm not terribly familiar with JavaScript best practices, so I wanted to get feedback on my approach.



Notes




  • I decided to implement the min heap using an array.


    • I filled the first element with a null value to make some of the math a little easier (in my opinion) - I know this is slightly more memory, but I thought the tradeoff was worth it



  • The actual MinHeap function is effectively a factory function (and not a constructor) that creates objects representing min heaps that wraps the underlying array implementation in closure.


    • The idea here was to minimize the public API (i.e. "privatize" as much of the internal implementation details as possible).

    • I explicitly named functions so that if any errors occurred, it would be easier to identify in the stack trace - I don't know if this preferred / matters



  • In the future, I could see this heap implementation expanding past a min heap to take a custom comparator, but I decided to keep it simple for the time being and simply use <.

  • I decided to write this in ES5 - I'll probably refactor this to use ES6 conventions in the future.


Questions



The questions I have are




  1. Is the factory function approach sound?

  2. Are there any JavaScript best practices that I've violated or ignored?

  3. Is my implementation flawed in any way?


Implementation



var MinHeap = function() {
var values = [null];

function getParentIndex(childIndex) {
return Math.floor(childIndex / 2);
}

function getChildIndices(parentIndex) {
var leftChild = parentIndex * 2;

return {
leftChild: leftChild,
rightChild: leftChild + 1,
};
}

function swap(firstIndex, secondIndex) {
var firstValue = values[firstIndex];

values[firstIndex] = values[secondIndex];
values[secondIndex] = firstValue;
}

function getSmallestNode(firstIndex, secondIndex) {
var firstValue = values[firstIndex];
var secondValue = values[secondIndex];

if (firstValue > secondValue) {
return {
value: secondValue,
index: secondIndex,
};
}

return {
value: firstValue,
index: firstIndex,
};
}

function add(value) {
var valueIndex,
parentIndex,
parentValue;

values.push(value);

valueIndex = getSize();
parentIndex = getParentIndex(valueIndex);
parentValue = values[parentIndex];

while (parentValue > value && parentIndex >= 1) {
swap(parentIndex, valueIndex);

valueIndex = parentIndex;
parentIndex = getParentIndex(valueIndex);
parentValue = values[parentIndex];
}
}

function remove() {
var firstValue = values[1],
lastValueIndex = values.length - 1,
lastValue = values.splice(lastValueIndex, 1)[0];

if (getSize() > 0) {
values[1] = lastValue;
lastValueIndex = 1;

var childIndices = getChildIndices(lastValueIndex);
var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

while (lastValue > smallestNode.value) {
swap(lastValueIndex, smallestNode.index);
lastValueIndex = smallestNode.index;

var childIndices = getChildIndices(lastValueIndex);
smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
}
}

return firstValue;
}

function getFirst() {
return values[1];
}

function getSize() {
return values.length - 1;
}

return {
add: add,
remove: remove,
getFirst: getFirst,
getSize: getSize,
};
};









share|improve this question



























    0














    Min Heap Implementation



    As an exercise, I wanted to implement a min heap using JavaScript.



    I'm not terribly familiar with JavaScript best practices, so I wanted to get feedback on my approach.



    Notes




    • I decided to implement the min heap using an array.


      • I filled the first element with a null value to make some of the math a little easier (in my opinion) - I know this is slightly more memory, but I thought the tradeoff was worth it



    • The actual MinHeap function is effectively a factory function (and not a constructor) that creates objects representing min heaps that wraps the underlying array implementation in closure.


      • The idea here was to minimize the public API (i.e. "privatize" as much of the internal implementation details as possible).

      • I explicitly named functions so that if any errors occurred, it would be easier to identify in the stack trace - I don't know if this preferred / matters



    • In the future, I could see this heap implementation expanding past a min heap to take a custom comparator, but I decided to keep it simple for the time being and simply use <.

    • I decided to write this in ES5 - I'll probably refactor this to use ES6 conventions in the future.


    Questions



    The questions I have are




    1. Is the factory function approach sound?

    2. Are there any JavaScript best practices that I've violated or ignored?

    3. Is my implementation flawed in any way?


    Implementation



    var MinHeap = function() {
    var values = [null];

    function getParentIndex(childIndex) {
    return Math.floor(childIndex / 2);
    }

    function getChildIndices(parentIndex) {
    var leftChild = parentIndex * 2;

    return {
    leftChild: leftChild,
    rightChild: leftChild + 1,
    };
    }

    function swap(firstIndex, secondIndex) {
    var firstValue = values[firstIndex];

    values[firstIndex] = values[secondIndex];
    values[secondIndex] = firstValue;
    }

    function getSmallestNode(firstIndex, secondIndex) {
    var firstValue = values[firstIndex];
    var secondValue = values[secondIndex];

    if (firstValue > secondValue) {
    return {
    value: secondValue,
    index: secondIndex,
    };
    }

    return {
    value: firstValue,
    index: firstIndex,
    };
    }

    function add(value) {
    var valueIndex,
    parentIndex,
    parentValue;

    values.push(value);

    valueIndex = getSize();
    parentIndex = getParentIndex(valueIndex);
    parentValue = values[parentIndex];

    while (parentValue > value && parentIndex >= 1) {
    swap(parentIndex, valueIndex);

    valueIndex = parentIndex;
    parentIndex = getParentIndex(valueIndex);
    parentValue = values[parentIndex];
    }
    }

    function remove() {
    var firstValue = values[1],
    lastValueIndex = values.length - 1,
    lastValue = values.splice(lastValueIndex, 1)[0];

    if (getSize() > 0) {
    values[1] = lastValue;
    lastValueIndex = 1;

    var childIndices = getChildIndices(lastValueIndex);
    var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

    while (lastValue > smallestNode.value) {
    swap(lastValueIndex, smallestNode.index);
    lastValueIndex = smallestNode.index;

    var childIndices = getChildIndices(lastValueIndex);
    smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
    }
    }

    return firstValue;
    }

    function getFirst() {
    return values[1];
    }

    function getSize() {
    return values.length - 1;
    }

    return {
    add: add,
    remove: remove,
    getFirst: getFirst,
    getSize: getSize,
    };
    };









    share|improve this question

























      0












      0








      0







      Min Heap Implementation



      As an exercise, I wanted to implement a min heap using JavaScript.



      I'm not terribly familiar with JavaScript best practices, so I wanted to get feedback on my approach.



      Notes




      • I decided to implement the min heap using an array.


        • I filled the first element with a null value to make some of the math a little easier (in my opinion) - I know this is slightly more memory, but I thought the tradeoff was worth it



      • The actual MinHeap function is effectively a factory function (and not a constructor) that creates objects representing min heaps that wraps the underlying array implementation in closure.


        • The idea here was to minimize the public API (i.e. "privatize" as much of the internal implementation details as possible).

        • I explicitly named functions so that if any errors occurred, it would be easier to identify in the stack trace - I don't know if this preferred / matters



      • In the future, I could see this heap implementation expanding past a min heap to take a custom comparator, but I decided to keep it simple for the time being and simply use <.

      • I decided to write this in ES5 - I'll probably refactor this to use ES6 conventions in the future.


      Questions



      The questions I have are




      1. Is the factory function approach sound?

      2. Are there any JavaScript best practices that I've violated or ignored?

      3. Is my implementation flawed in any way?


      Implementation



      var MinHeap = function() {
      var values = [null];

      function getParentIndex(childIndex) {
      return Math.floor(childIndex / 2);
      }

      function getChildIndices(parentIndex) {
      var leftChild = parentIndex * 2;

      return {
      leftChild: leftChild,
      rightChild: leftChild + 1,
      };
      }

      function swap(firstIndex, secondIndex) {
      var firstValue = values[firstIndex];

      values[firstIndex] = values[secondIndex];
      values[secondIndex] = firstValue;
      }

      function getSmallestNode(firstIndex, secondIndex) {
      var firstValue = values[firstIndex];
      var secondValue = values[secondIndex];

      if (firstValue > secondValue) {
      return {
      value: secondValue,
      index: secondIndex,
      };
      }

      return {
      value: firstValue,
      index: firstIndex,
      };
      }

      function add(value) {
      var valueIndex,
      parentIndex,
      parentValue;

      values.push(value);

      valueIndex = getSize();
      parentIndex = getParentIndex(valueIndex);
      parentValue = values[parentIndex];

      while (parentValue > value && parentIndex >= 1) {
      swap(parentIndex, valueIndex);

      valueIndex = parentIndex;
      parentIndex = getParentIndex(valueIndex);
      parentValue = values[parentIndex];
      }
      }

      function remove() {
      var firstValue = values[1],
      lastValueIndex = values.length - 1,
      lastValue = values.splice(lastValueIndex, 1)[0];

      if (getSize() > 0) {
      values[1] = lastValue;
      lastValueIndex = 1;

      var childIndices = getChildIndices(lastValueIndex);
      var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

      while (lastValue > smallestNode.value) {
      swap(lastValueIndex, smallestNode.index);
      lastValueIndex = smallestNode.index;

      var childIndices = getChildIndices(lastValueIndex);
      smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
      }
      }

      return firstValue;
      }

      function getFirst() {
      return values[1];
      }

      function getSize() {
      return values.length - 1;
      }

      return {
      add: add,
      remove: remove,
      getFirst: getFirst,
      getSize: getSize,
      };
      };









      share|improve this question













      Min Heap Implementation



      As an exercise, I wanted to implement a min heap using JavaScript.



      I'm not terribly familiar with JavaScript best practices, so I wanted to get feedback on my approach.



      Notes




      • I decided to implement the min heap using an array.


        • I filled the first element with a null value to make some of the math a little easier (in my opinion) - I know this is slightly more memory, but I thought the tradeoff was worth it



      • The actual MinHeap function is effectively a factory function (and not a constructor) that creates objects representing min heaps that wraps the underlying array implementation in closure.


        • The idea here was to minimize the public API (i.e. "privatize" as much of the internal implementation details as possible).

        • I explicitly named functions so that if any errors occurred, it would be easier to identify in the stack trace - I don't know if this preferred / matters



      • In the future, I could see this heap implementation expanding past a min heap to take a custom comparator, but I decided to keep it simple for the time being and simply use <.

      • I decided to write this in ES5 - I'll probably refactor this to use ES6 conventions in the future.


      Questions



      The questions I have are




      1. Is the factory function approach sound?

      2. Are there any JavaScript best practices that I've violated or ignored?

      3. Is my implementation flawed in any way?


      Implementation



      var MinHeap = function() {
      var values = [null];

      function getParentIndex(childIndex) {
      return Math.floor(childIndex / 2);
      }

      function getChildIndices(parentIndex) {
      var leftChild = parentIndex * 2;

      return {
      leftChild: leftChild,
      rightChild: leftChild + 1,
      };
      }

      function swap(firstIndex, secondIndex) {
      var firstValue = values[firstIndex];

      values[firstIndex] = values[secondIndex];
      values[secondIndex] = firstValue;
      }

      function getSmallestNode(firstIndex, secondIndex) {
      var firstValue = values[firstIndex];
      var secondValue = values[secondIndex];

      if (firstValue > secondValue) {
      return {
      value: secondValue,
      index: secondIndex,
      };
      }

      return {
      value: firstValue,
      index: firstIndex,
      };
      }

      function add(value) {
      var valueIndex,
      parentIndex,
      parentValue;

      values.push(value);

      valueIndex = getSize();
      parentIndex = getParentIndex(valueIndex);
      parentValue = values[parentIndex];

      while (parentValue > value && parentIndex >= 1) {
      swap(parentIndex, valueIndex);

      valueIndex = parentIndex;
      parentIndex = getParentIndex(valueIndex);
      parentValue = values[parentIndex];
      }
      }

      function remove() {
      var firstValue = values[1],
      lastValueIndex = values.length - 1,
      lastValue = values.splice(lastValueIndex, 1)[0];

      if (getSize() > 0) {
      values[1] = lastValue;
      lastValueIndex = 1;

      var childIndices = getChildIndices(lastValueIndex);
      var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

      while (lastValue > smallestNode.value) {
      swap(lastValueIndex, smallestNode.index);
      lastValueIndex = smallestNode.index;

      var childIndices = getChildIndices(lastValueIndex);
      smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
      }
      }

      return firstValue;
      }

      function getFirst() {
      return values[1];
      }

      function getSize() {
      return values.length - 1;
      }

      return {
      add: add,
      remove: remove,
      getFirst: getFirst,
      getSize: getSize,
      };
      };






      javascript heap






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 15 mins ago









      Jae Bradley

      822717




      822717






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210959%2fmin-heap-implementation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210959%2fmin-heap-implementation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Quarter-circle Tiles

          build a pushdown automaton that recognizes the reverse language of a given pushdown automaton?

          Mont Emei