Skip to content
Advertisement

NodeJs heap-js module: Heap is not a constructor

I am trying to initialize a minimum heap/priority queue in my server.js using the head-js module (https://github.com/ignlg/heap-js). When I run my code, I receive the following error:

var minHeap = new Heap(customComparator);

TypeError: Heap is not a constructor

However, according to the documentation, I am initializing the heap correctly, putting in a custom constructor as the parameter. Below is my code:

var Heap = require("heap-js");
// Build a minimum heap of size k containing the k cities with the most active users
var customComparator = (city1, city2) => citySizes[city1] - citySizes[city2];
var minHeap = new Heap(customComparator);

Advertisement

Answer

There’s a difference between using heap-js library in CommonJS and ES6 modules.

When requireing (i.e. CommonJS) you need to destruct out the Heap class from the object returned, like so:

const { Heap } = require('heap-js') // correct
const Heap = require('heap-js') // incorrect

Whereas, you have to do the opposite in ES6, as shown below:

import Heap from 'heap-js' // correct
import { Heap } from 'heap-js' // incorrect
Advertisement