Activity: Using a Third-Party Package for the Previous math.js Code

Before You Begin

This activity will build upon the, Running Basic Node.js activity of this chapter.

Aim

If the argument is a single array, sum up the numbers, and if it's more than one array, first combine the arrays into one before summing up. We will use the concat() function from lodash, which is a third-party package that we will install.

Scenario

We want to create a new function, sumArray, which can sum up numbers from one or more arrays.

Steps for Completion

  1. Inside Lesson-1, create another folder called activity-b.
  2. On the Terminal, change directory to activity-b and run the following command:
npm init
  1. This will take you to an interactive prompt; just press Enter all the way, leaving the answers as suggested defaults. The aim here is for us to get a package.json file, which will help us organize our installed packages.
  2. Since we will be using lodash, let's install it. Run the following command:
npm install lodash--save

Notice that we are adding the --save option on our command so that the package installed can be tracked in package.json. When you open the package.json file created in step 3, you will see an added dependencies key with the details.

  1. Create a math.js file in the activity-b directory and copy the math.js code from Activity, Running Basic Node.js into this file.
  2. Now, add the sumArray function right after the sum function.
  3. Start with requiring lodash, which we installed in step 4, since we are going to use it in the sumArray function:
const _ = require('lodash');
  1. The sumArray function should call the sum function to reuse our code. Hint: use the spread operator on the array. See the following code:
function sumArray() 
{
let arr = arguments[0];
if (arguments.length > 1)
{
arr = _.concat(...arguments);
}
// reusing the sum function
// using the spread operator (...) since
// sum takes an argument of numbers
return sum(...arr);
}
  1. At the end of the file, export the three functions, add, sum, and sumArray with module.exports.
  2. In the same activity-b folder, create a file, index.js.
  3. In index.js file, require ./math.js and go ahead to use sumArray:
// testing
console.log(math.sumArray([10, 5, 6])); // 21
console.log(math.sumArray([10, 5], [5, 6], [1, 3])) // 30
  1. Run the following code on the Terminal:
node index.js

You should see 21 and 30 printed out.


The solution files are placed at Code/Lesson-1/activitysolutions/activity-b.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset