Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exercism > Javascript > Hamming exercise: Getting 'undefined is not a function' error

Can someone tell me what I'm doing wrong here? The test sees the 'compute' function as undefined, and I'm completely out of ideas why.

Here is the error I'm getting:

Failures:

1) Hamming no difference between identical strands
   Message:
     TypeError: undefined is not a function
   Stacktrace:
     TypeError: undefined is not a function
    at null.<anonymous> (C:\Users\Schann\exercism\javascript\hamming\hamming_test.spec.js:6:12)

2) Hamming complete hamming distance for single nucleotide strand
   Message:
     TypeError: undefined is not a function
   Stacktrace:
     TypeError: undefined is not a function
    at null.<anonymous> (C:\Users\Schann\exercism\javascript\hamming\hamming_test.spec.js:10:12)

Finished in 0.041 seconds
2 tests, 2 assertions, 2 failures, 0 skipped

//-------------------
// Hamming.js
//-------------------
var Hamming = function() {
    var compute = function(input1, input2) {
        var diff = 0;
        for (i = 0; i < input1.length; i++) {
            if (input1[i] != input2[i]) {
                diff = diff + 1;            
            };
        };
        return diff;
    };
};

module.exports = Hamming;

//-------------------
// hamming_test.spec.js 
//-------------------

var compute = require('./hamming').compute;

describe('Hamming', function () {

  it('no difference between identical strands', function () {
    expect(compute('A', 'A')).toEqual(0);
  });

  it('complete hamming distance for single nucleotide strand', function () {
    expect(compute('A','G')).toEqual(1);
  });

[rest truncated]

});
like image 879
Shaahin Sh Avatar asked Oct 29 '14 21:10

Shaahin Sh


1 Answers

Your compute function never gets exported, it's only a local variable of the Hamming function.

What you want to do is more like :

var Hamming = {
  compute: function(input1, input2) {
    var diff = 0;
    for (i = 0; i < input1.length; i++) {
      if (input1[i] != input2[i]) {
        diff = diff + 1;
      }
    }
    return diff;
  }
};

module.exports = Hamming;

My guess is that you have a background from a classical programming language like Java and C++, and are seeing your Hamming function as a class declaration with a compute member.

like image 65
Valentin Waeselynck Avatar answered Sep 22 '22 05:09

Valentin Waeselynck