Ads Top

Node Basics: Add Numbers Provided From Command Line

I was recently browsing around for some resources to practice some basic(and not so basic) practice examples/courses. I came across https://nodeschool.io. More specifically, this section, the workshoppers section. Basically, these are npm modules you can install globally and they each have individual sections that you can solve and move on.

During downtime, and because you don't do challenges like this everyday, I will work on one or two and post solutions that I find interesting enough to post. The first one I am going to do is the learnyounode track.
All of these challenges can be solved by installing node on your machine and running node from the command line.

The Problem
Write a program that accepts numbers from the command line when calling your script. These numbers should be added and display the sum of the numbers given.

Run the program like this from the command line

node program.js 1 2 3


Tips
Get the arguments like this

console.log(process.argv)

Keep in mind that the arguments are presented as an array, and the list of numbers to be added do not start until array element 2. Also, they are stored as strings.

For example - when running node program.js 1 2 3 and getting the arguments via console.log(process.argv)
It will actually look like this
[ 'node', '/path/to/addarguments.js', '1', '2', '3' ]

Notice the numbers are strings. We need to be able to add those as numbers so we need to account for that.

Walking through a solution
1: Get the arguments padded in
2: Slice the array so that it starts at element 2 and then get the length
3: Use forEach to loop over the arguments and add them to a sum variable
4: Print the answer

Solution
Calling this with the example from above
node program.js 1 2 3
The result would read
The sum = 6

No comments:

Powered by Blogger.