2

I'm trying to write a program that takes any number of command line arguments, in this case, strings and reverses them, then outputs them to the console. Here is what I have so far:

let CL = process.argv.slice(2);
let extract = CL[0];

function reverseString(commandInput) {
  var newString = "";
  for (var i = commandInput.length - 1; i >= 0; i--) {
    newString += commandInput[i];
  }
  return console.log(newString);
}

let call = reverseString(extract);

I can't figure out a way to make this work for multiple arguments in the command line such as:

node reverseString.js numberOne numberTwo

which would result in output like this:

enOrebmun owTrebmun 

however it works fine for a single argument such as:

node reverseString.js numberOne
4
  • 1
    Not clear what result you're trying to end up with. Maybe CL.join(" ").reverse(). Commented Feb 17, 2019 at 3:00
  • 1
    let calls = CL.map(reverseString); then log them if you want like: console.log(calls.join("\n")); Commented Feb 17, 2019 at 3:01
  • 1
    You simply have to perform the operation for each item in CL - for (const x in CL) { console.log(reverseString(x)) } Commented Feb 17, 2019 at 3:04
  • 1
    you should change return console.log(newString) to return newString - console.log doesn't return anything. Commented Feb 17, 2019 at 4:08

1 Answer 1

1

You need to run your reverseString() function on each of the argv[n...] values passed in. After correctly applying the Array.prototype.splice(2) function, which removes Array index 0 and 1 (containing the command (/path/to/node) and the /path/to/module/file.js), you need to iterate over each remaining index in the array.

The Array.prototype.forEach method is ideal for this, instead of needing a for loop or map. Below is using the OP code and is the minimal program (without much refactor) needed for desired output.

    let CL = process.argv.slice(2);

    function reverseString(commandInput) {
      var newString = "";
      for (var i = commandInput.length - 1; i >= 0; i--) {
        newString += commandInput[i];
      }
      return console.log(newString);
    }

    CL.forEach((extract)=>reverseString(extract))

Here is me running this code from the terminal: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.