Reputation: 3
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)
Upvotes: 0
Views: 74
Reputation: 92461
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.
Upvotes: 2