Michelle Michelle - 4 years ago 168
Javascript Question

Calling sub functions

This is a program to find the nth fibonacci number.

var fib = (function() {
var save = [];
var i = 0;

return {
"getNum": function(input) {
this.input = input;

if (input === 0) {
console.log("Invalid input");
}

save[i] = i;
save[i + 1] = i + 1;
save[i + 2] = i + 1;
i = 2;

for (i >= 2; i < input; i = i + 1) {
save[i + 1] = save[i] + save[i - 1];
}

console.log(save[i - 1]);
}
}
}());

fib.getNum(4);


My question is when I implement this problem in the following way, it doesn't work. I understand this is because I am not calling the sub-functions and only calling the main function. Is there a better pattern we can use that will keep the code organised and we won't have to make calls to so many functions?

var fib = (function() {
var save = [];
var i = 0;

return {
"getNum": function(input) {
this.input = input;

function valid() {
if (input === 0) {
console.log("Invalid input");
}
}

function config() {
save[i] = i;
save[i + 1] = i + 1;
save[i + 2] = i + 1;
i = 2;
}

function nthNum() {
for (i >= 2; i < input; i = i + 1) {
save[i + 1] = save[i] + save[i - 1];
}
console.log(save[i - 1]);
}
}
}
}());

fib.getNum(4);

Answer Source

You can think of using closure to create private and public functions.If you see the below code only _getNum function is exposed.

var fib = (function() {
    var save = [];
    save[0] = 0;
    save[1] = 1;
    var i = 0;

    //This will validate the number
    // This function can be avoided and make _getNum do the same

    function _valid(input){
      console.log("Method Executing:_valid");
      input === 0 ? console.log('Invalid Input') : _nthNum(input); 
     }

    // Will calualte the series.
    // This is a private function
    function _nthNum(input) {
     console.log('Method Executing:_nthNum');
        for (i = 2; i<=input; i++) {
             save[i] = save[i-2] + save[i - 1];
         }
          console.log(save.pop());
    }

    // Private Function
    function _getNum(input){
            console.log("Method Executing :_getNum" ,input);
            _valid(input);
        }

    //Expose the private function
  return {
   getNum :_getNum      // Expose _getNum
  }
}());
fib.getNum(0);
fib.getNum(4);
fib.getNum(7);

WORKING COPY

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download