I am writing a node module that tests an array of words against one word to see if it is an anagram (I know the functionality below for testing that is not correct yet), but I'm running into the error that's described in the title. From what I understand, it means that the object that should contain the method 'matches' is not set, and I'm having trouble understanding how I handle this. Here is the contents of the anagram module:
var Anagram = function(a){
this.word = a;
this.matches = function(array){
var found = [];
for(var i = 0; i < array.length; i++){
if(is_anagram(array[i],this.word)) found.push(array[i]);
}
return found;
}
};
function is_anagram(word, check){
if(word.length == check.length)return true;
return false;
}
module.exports = Anagram;
In my test file (using Jasmine:
var anagram = require('./anagram');
describe('Anagram', function() {
it("no matches",function() {
var subject = anagram("diaper");
var matches = subject.matches([ "hello", "world", "zombies", "pants"]);
expect(matches).toEqual([]);
});
});
I'm still a bit new to js. What am I missing here?
var subject = anagram("diaper");
should be
var subject = new anagram("diaper");
You have created a constructor function, but you are using it like a normal function.
For clarity, I'd probably keep the capitalization consistent as well:
var Anagram = require('./anagram');
with
var subject = new Anagram("diaper");
Since you can't change the testing code to use new, then you should change the structure of your program to create an object instance yourself.
function is_anagram(word, check){
if (word.length == check.length) return true;
return false;
}
module.exports = function(word){
// Just return an object with a single 'matches' function
return {
matches: function(array){
var found = [];
for(var i = 0; i < array.length; i++){
if (is_anagram(array[i], word)) found.push(array[i]);
}
return found;
}
};
};
Or perhaps even clearer:
module.exports = function(word){
return {
matches: function(array){
return array.filter(function(item){
return is_anagram(item, word)
});
}
};
};
Based on your constrains you need to add a 'return this' in the end of the Anagram function:
var Anagram = function(a){
this.word = a;
this.matches = function(array){
var found = [];
for(var i = 0; i < array.length; i++){
if(is_anagram(array[i],this.word)) found.push(array[i]);
}
return found;
}
return this;
};
Additionally I would suggest to put your is_anagram function inside of the Anagram.