Calculate the sum of an infinite number of parameters using the Caporal npm package in JavaScript

Is there a way to sum an infinite number of parameters using caporal npm?

var prog = require('caporal');

prog
    .version('1.0.0')
    .command('sum', 'inputnumber')
    .argument('[env...]', 'Other environments')
    .action((args) => {
        env:[]
        console.log(args);
    })

prog.parse(process.argv);

This code will print: 
./cli sum 1 2 3 4
{ env: [ '1', '2', '3', '4' ] }

How can I split that array and calculate the sum?

I already know how to sum using two defined parameters

var prog = require('caporal');
prog
    .version('1.0.0')
    .command('sum', 'inputnumber')
    .argument('<n1>','first number')
    .argument('<n2>','second number')
    .action(function(args) {
        var result = parseInt(args.n1) + parseInt(args.n2);
        console.log(result);
    });

prog.parse(process.argv);

./cli sum 1 2
3

Answer №1

Resolved the issue on my own

 prog
        .version('1.0.0')
        .command('sum', 'inputtext')
        .argument('[env...]', 'Other environments')
        .action((args) => {
            var s = 0;
            for(var i=0; i<args.env.length; i++)
                s += parseInt(args.env[i]);
            console.log(s);
        })

    prog.parse(process.argv);

    ./cli sum 1 2 3 4
    10

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jquery makes it easy to create interactive hide and show effects

The main concept is to display the element upon clicking and hide it when there is any mouse click event. Below is the HTML code I'm using: <ul> <li> <span class="name">Author 1</span> <span class="affiliation"&g ...

Angular 9 date input and selection

I am currently troubleshooting why the attribute value on an input type date is not working with Angular 9. <input type="date" [max]="dateConfig.max" [min]="dateConfig.min" name="date" [value]="dateConfig.val ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

Tips for dynamically inserting a new column into a table at any position other than the beginning or end

I have created a dynamic table where rows and columns can be added dynamically. However, I am facing an issue where I am unable to add a new column between the first and last column of the table. Currently, new columns are only being added at the end. $ ...

Guide to retrieving fresh information from an API using a desktop application built on node and electron

Looking for advice on efficiently retrieving new order data from the Shopify API for a private desktop application I'm working on. Should I query the API at regular intervals while the application is active, or is there a way to implement webhooks in ...

What steps should I take to enable Google Maps style on mobile devices?

Hi there! I'm having some trouble styling my Google map. Sometimes the style loads correctly in browsers, and sometimes it doesn't. Another issue I've noticed is that when I view the page on mobile platforms like Android Chrome, iOS Safari, ...

Prevent tab key focus in jQuery UI autocomplete

Sharing my own answer here: Here is the HTML code I am working with: <select id="genre-select"> <option value="-1">Please select</option> <option value="1">One</option> <option value="2">Two ...

Each time I use console.log to display a user's radio button choice, the output is consistently lagging by one step

It seems that I am experiencing an issue where the console.log output for a user's radio button selection is always one step behind. This occurs even though I have initially set the default radio button selection to "all". For example, when a user cli ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

Adjust the prop value whenever there is a modification in the Vuex store

Following a successful mutation to the vuex store (state.posts.post.comments) with the use of this code snippet and implementing Vue.set for Vue to acknowledge the addition of an object property: store/modules/post.js const mutations = { [types.SET_P ...

Node.js script to convert server time to a specific local time

I have this code running on my server-side nodejs for timezone conversion. convertNowToTimezone = (localOffset) => { let d = new Date(); let millis = d.getTime() + (d.getTimezoneOffset() * 60000); //converting server local time to UTC milliseconds ...

Steps to handling and resolving a vulnerable npm security issue regarding semver that is susceptible to Regular Expression Denial of Service

Encountering an error in my azure pipeline: The issue is with semver, which has a vulnerability to Regular Expression Denial of Service. Severity: moderate More info When trying to resolve the error by adding semver to my resolutions in package.json: &q ...

Finding the least common multiple (LCM) of two or three numbers using JavaScript

I have been working on a code snippet to find the Greatest Common Denominator (GCD) of two or three numbers. Here is what I have so far: Math.GCD = function(numbers) { for (var i = 1 ; i < numbers.length ; i++){ if (numbers[i] || numbers[i] = ...

Refreshing Child's Activities

In my scenario, I am displaying data in a child action and utilizing buttons to modify the displayed information. Here is an example of how I am achieving this: Index.cshtml <head> <script type="text/javascript"> $("#RefreshView").on ...

Tips for showcasing several thumbnails simultaneously as you upload images on a webpage with HTML and JavaScript

function displayImage(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#selectedImage') .attr('src', e.target.result) }; reader.read ...

How can we trigger an AJAX function for every checkbox depending on its current state?

My jquery function has a peculiar behavior. Whenever I interact with the checkboxes, whether checking both, unchecking both, or checking one and unchecking the other, only the last checkbox edited triggers the method. In other words, it only 'removes& ...

Exploring Angular 10: Managing Two Promises in ngOnInit

I am currently working on integrating the Strava API into my Angular app. To summarize briefly: When a user clicks on a button to connect to Strava They are redirected to Strava for authentication (using PKCE) Strava then redirects back to my app with a ...

Using Jest's moduleNameMapper with Next.js without TypeScript

I've been encountering some challenges trying to implement moduleNameMapper in NextJS using JavaScript. In this particular project, TypeScript is not being utilized. Next: 12.2.5 React: 18.2.0 Jest: 29.0.1 Jest environment jsdom: 29.0.1 Below is the ...

NextJS: When attempting to serialize the `function` as JSON, an error occurs as it is not a JSON serializable data type

In my Firestore database, I have a collection named "mentor" that contains documents with three fields: "name", "email", and "linkedin". My goal is to fetch all the documents from this collection and pass them as props so that I can render their fields on ...