0

I am trying to make and test a trie in javascript and have split the nodes, trie and test into separate files. I am using node.js to share the code between files. I have tried messing around with the export and require but keep getting a type error saying that the import is not a constructor.

In trienode.js

function trieNode(val, par) {
  this.value = val;
  this.children = {};
  this.isWord = false;
  this.freq = 0;
  this.parent = par;
}

trieNode.prototype.getValue = function() {
  return this.value;
}

module.exports.tn = trieNode();

In trie.js

var trieNode = require('./trienode.js').tn;

function Trie() {
  console.log('initialize trie');
  console.log(typeof trieNode);
  this.root = new trieNode(null);
  this.saved = {}
  this.current;
}

Trie.prototype.insert = function(word) {
}

Trie.prototype.findSuggestions = function(prefix) {
}
module.exports = Trie();

In test.js

var Trie = require('./trie.js');
var trieNode = require('./trienode.js').tn;

var tr = new Trie();

tr.insert("boot");
tr.insert("boot");
tr.insert("boot");
tr.insert("book");
tr.insert("book");
tr.insert("boom");
var sug = tr.findSuggestions("boo");
for(s in sug) {
  console.log(s);
}

This is the error I'm getting

TypeError: trieNode is not a constructor
    at Trie (C:\Users\agnu\Desktop\autocomplete\trie.js:6:15)
    at Object.<anonymous> (C:\Users\agnu\Desktop\autocomplete\trie.js:94:18)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\agnu\Desktop\autocomplete\test.js:1:74)
0

1 Answer 1

2

You are exporting the results of the function, not the function itself.

If you want to call the function after importing it, you need to just export the functions:

module.exports.tn = trieNode;

and

module.exports = Trie;

Then, after importing them, you call the functions.

Sign up to request clarification or add additional context in comments.

3 Comments

I didn't catch this problem, but thanks for the post. Will it work passing one parameter when the constructor expects two?
@RyanWilson you don't have to pass all arguments to a function. If you don't it will just have the value of undefined in the function.
@MarkMeyer Ah, thanks for clarifying that. I am used to compiler errors in C# if you try to call a constructor with less parameters than the one defined. I'll remove my comment. +1 from me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.