Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Getting started with Node.js CHAPTER 8 347


module.exports = {
addition: add,
subtraction: subtract
}

In the simple_math.js file, the require function references the call_counter.js module. The
use of the ‘./call_counter’ syntax indicates that this is a local module in the current folder as
opposed to a package. The reference is assigned to the call_counter variable. The add and
subtract functions call the call_counter variable, which references the count_call function. This
module exports two functions, so an object is created to provide access to these functions. In
this case, the addition method references the add function, whereas the subtraction method
references the subtract function. It’s more typical for the method name to be the same as the
function name, but this example demonstrates that they can be different.
The next module created in the lib folder is advanced_math.js, which has the following
code.
var call_counter = require('./call_counter');

function multiply(x, y){
call_counter();
return x * y;
}

function divide(x, y){
call_counter();
return x / y;
}

function fibo(count) {
call_counter();
return private_fibo(count)
}

function private_fibo(count, counter, first, second) {
if (count == 0) return 0;
if (counter == undefined) {
counter = 1
first = 1;
second = 2;
}
result = first + second;
if (counter == count) return result;
private_fibo(count, ++counter, second, result)
return result;
}

module.exports = {
multiplication: multiply,
division: divide,
fibonacci : fibo
}
Free download pdf