Search code examples
javascriptnode.jskalman-filter

prototype.Function is not being exported in node.js


I found this javascript Kalman filter library online and I wanted to use it with my node.js application. As I wanted to include this js file into my node.js application, I tried to export the required functions ( added module.exports as shown below) .

module.exports = {

  KalmanModel : function(){

    function KalmanModel(x_0,P_0,F_k,Q_k){
      this.x_k  = x_0;
      this.P_k  = P_0;
      this.F_k  = F_k;
      this.Q_k  = Q_k;
    }

    KalmanModel.prototype.update =  function(o){
      // code 
    }

    return KalmanModel;
  },

  KalmanObservation : function(){

    function KalmanObservation(z_k,H_k,Q_k){
      this.z_k = z_k;//observation
      this.H_k = H_k;//observation model
      this.R_k = R_k;//observation noise covariance
    }

    return KalmanObservation;
  }
};

But when I try to run the following piece of code

Code:

var kal =require('./kalman');
var observationVal = observationValues;
var x_0 = $V([observationVal[0]]);
var P_0 = $M([[2]]);
var F_k=$M([[1]]);
//process noise
var Q_k=$M([[0]]);
var KM = kal.KalmanModel(x_0,P_0,F_k,Q_k);
//value we measure
var z_k = $V([observationVal[0]]);
var H_k = $M([[1]]);
var R_k = $M([[4.482]]);
var KO = kal.KalmanObservation(z_k,H_k,R_k);

for (var i=1;i<10;i++){
z_k = $V([observationVal[i]]);
KO.z_k=z_k;
KM.update(KO);

I get an error

TypeError: object is not a function.

It looks like method defined with prototype is not getting exported. What am I doing wrong here?


Solution

  • Well if you don't wanna change much in the existing source code you can do this. Don't remove the implicit function call ie : (function(){//code})(); and i think you should be set.

    module.exports = {
    
        KalmanModel : (function(){
    
            function KalmanModel(x_0,P_0,F_k,Q_k){
              this.x_k  = x_0;
              this.P_k  = P_0;
              this.F_k  = F_k;
              this.Q_k  = Q_k;
            }
    
            KalmanModel.prototype.update =  function(o){
              // code 
            }
    
            return KalmanModel;
        })(),
    
        KalmanObservation : (function(){
    
            function KalmanObservation(z_k,H_k,Q_k){
              this.z_k = z_k;//observation
              this.H_k = H_k;//observation model
              this.R_k = R_k;//observation noise covariance
            }
    
            return KalmanObservation;
        })()
    };
    

    Or simply append the following in the library kalman.js

    module.exports = {
        myKalmanModel : KalmanModel,
        myKalmanObservation : KalmanObservation
    }
    

    and access as

    var KM = kal.myKalmanModel(x_0,P_0,F_k,Q_k);