SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member randie's Avatar
    Join Date
    Oct 2008
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    BinaryHeap scoreFunction that does nothing?

    On page 27 of your "Jump Start Node.js" book, in the chapter02/lib/exchange.js excerpt- please explain the purpose of a BinaryHeap scoreFunction (in red below) that simply returns the argument you send it (basically, a no-op)?

    Code:
    function createBinaryHeap(orderType) {
        return new BinaryHeap(function(x) { return x; }, orderType);
    }

  2. #2
    SitePoint Author
    Join Date
    Nov 2012
    Posts
    48
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi randie, a detailed explanation of the BinaryHeap implementation can be found here:

    http://eloquentjavascript.net/appendix2.html

    To quote the relevant section:

    Here is the full code of a binary heap implementation. Two things to note are that, instead of directly comparing the elements put into the heap, a function (scoreFunction) is first applied to them, so that it becomes possible to store objects that can not be directly compared.
    In other words, the function appears trivial because we're just comparing numbers. However imagine we are sorting something like an Employee object. Because there is no natural way of comparing Employee objects we would need to implement a nontrivial scoring function to compare them, perhaps by id:

    Code:
    function(employee) {
    	return employee.id; 
    }

  3. #3
    SitePoint Member randie's Avatar
    Join Date
    Oct 2008
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the response, Don!

    I guess I was confused by having to provide and call a function that did nothing, incurring the function call overhead for no gain. I probably would have written the BinaryHeap code to only use a scoreFunction if one is provided, and if none (null) is provided, have it simply compare the contents directly.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •