Can you create a while loop that continuously asks for user input, stores the responses, and then makes them accessible in an array?

When developing a Yeoman generator, the necessary dependencies can be found at https://github.com/sboudrias/mem-fs-editor#copytplfrom-to-context-settings and https://github.com/SBoudrias/Inquirer.js/.

The main goal is to prompt the user with a question and repeat it as needed. For instance, if the user chooses to add more details, the answer will be recorded. If the response is 'no' or blank, the prompt should stop.

Subsequently, all answers should be stored in an array that can be passed to another function for listing out responses. Take a look at the current code:

askForTest1: function () {
    if (this.type == 'foundation5') {
        var cb = this.async();

        var prompts = {
            type: 'input',
            name: 'test1',
            message: chalk.yellow('  What is your favorite movie'),
            default: 'Star Wars!'
        };

        this.prompt(prompts, function (props) {
            this.templatedata.test1 = props.test1;

            cb();
        }.bind(this));
    }
},

Following the prompts, there is a copyTpl object that assigns options for creating templates. This is the intended output I am aiming for within the same index.js file:

this.fs.copyTpl(
      this.templatePath('/index2.html'),
      this.destinationPath('app/index2.html'),
      { title: [this.templatedata.test1-a, this.templatedata.test1-b, this.templatedata.test1-c, ...], h1: this.applicationName }
);

Ultimately, the template code mentioned should yield the following result:

using

This would generate:

using foo1
using foo2

Is this achievable? How should I approach implementing this functionality?

Answer №1

This task involves a simple programming exercise.

The method uses recursion to repeatedly ask the user a question. If the user responds with "yes, add more", the function is called again.

Here is an example of how it can be implemented:

initialize: function () {
  this.collection = [];
},

askItem: function (callback) {
  callback = callback || this.async();

  var prompts = [{
      type: 'input',
      name: 'item',
      message: chalk.yellow('  Enter your favorite item'),
      default: 'Star Wars!'
  }, {
    type: 'confirm',
    name: 'askAgain',
    message: 'Ask again?'
  }];

  this.prompt(prompts, function (properties) {
    this.collection.push(properties.item);
    if (properties.askAgain) {
      this.askItem(callback);
    } else {
      callback();
    }
  }.bind(this));
}

Answer №2

If you're looking for a solution, try something along these lines:

function() {
    var info = {
        times: [],
        title: undefined,
        type: undefined
    };

    function askQuestion(question, callback) {
        self.prompt(question, function (response) {
            if(response.answer != "done") {
                info.times.push(response.time);
                askQuestion(question, callback);
            } else {
                callback();
            }
        });
    }

    var callback = this.async(),
        self = this,
        movieTypeQuestion = {
            type: 'input',
            name: 'movieType',
            message: chalk.yellow('What is your favorite type of movie?'),
            default: 'Action'
        },
        movieTitleQuestion = {
            type: 'input',
            name: 'movieTitle',
            message: chalk.yellow('What is your favorite movie?'),
            default: 'Tron: Legacy'
        }
        movieTimeQuestion = {
            type: 'input',
            name: 'time',
            message: chalk.yellow('When can you watch a movie? (enter \'done\' when you are done entering times)'),
            default: '8PM'
        };

    //Prompt for movie type and title
    this.prompt([movieTypeQuestion, movieTitleQuestion], function (response) {
        info.title = response.movieTitle;
        info.type = response.movieType;

        //Keep asking for movie times
        askQuestion(movieTimeQuestion, function() {
            console.log('done');

            callback();
        });
    }.bind(this));
}

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

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

Tips for ensuring that an Ajax request successfully executes when a page loads

I have a question about implementing an AJAX request in my code. Currently, I have the text on the screen updating when a dropdown input is selected using 'onchange'. However, I also want this same behavior to occur on page load, but I am struggl ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Generating charts using JSON data with the help of JavaScript

Hi there! I have a JSON file shown in the first image and I would like to create a chart similar to the one in the second image using JavaScript (using any library). Can anyone provide me with a simple example code on how to achieve this? ...

What is the underlying process of npm's cache when applied to a git branch?

We've encountered a fascinating edge case that I wanted to share in hopes of getting some insights. Our project is linked to an npm module through a git repository URL: dependencies: { "whatever": "git+ssh://<a href="/cdn-cgi/l/email-protection ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

What is the best way to compare two arrays of objects and then append a new key to the objects in the second array?

Consider the following arrays where you are tasked with comparing them and returning a filtered version of array two containing elements found in array one: const array1 = [ { name: "Jack", age: 54, title: "IT Engineer" }, { na ...

Sorting the keys of objects within an array

Currently, I am in the midst of an evaluation where I have the freedom to utilize any resources at my disposal. The task at hand involves using the .filter method to remove objects without a specific key. Here is the provided prompt... Create a function n ...

I'm feeling completely lost trying to understand cors in conjunction with fetch, particularly when an options request is

I am using whatwg fetch in the code snippet below: const headers = new Headers(); //uncommenting this causes the preflight options request to be sent //headers.append('x-something', 'foo'); const response = await fetch(&apos ...

Updating the default date format input fields for React-bootstrap-daterangepicker in the United States

Hey there, I'm a newcomer to the world of React and Javascript and I've encountered an issue that has me stumped. I'm trying to change the default US dateformat in my React-bootstrap-daterangepicker, but I'm struggling to figure out how ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Steps for converting SCSS to CSS using node-sass

I have a main.scss file with numerous imports from other .scss files. Whenever I make changes to any of the *.scss files, the master.css file is automatically generated. I rely solely on NPM for my build process and do not use Gulp or Grunt! It's imp ...

Downloading EJS File instead of Displaying on Express.js Router

As I embark on the journey of developing a live video sharing/watching feature using Pure Node.js and without relying on any frameworks, an unexpected issue arose in the middle of the process. The problem occurred when Express started downloading an EJS fi ...

Do not make changes to the package.json file while performing an npm audit fix

After updating my npm version, I noticed that npm audit is a new feature. However, when I use npm audit fix, some of the package versions in my package.json file are changed. I simply want to ensure that my packages remain consistent with those of my cow ...

Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involve ...

Issue with node module: critical error LNK1107 - file is invalid or corrupted and cannot be read at memory address 0x2BE03E

I recently set up Gatsby and began using the Casper Gatsby Starter Kit. After successfully running `npm install`, I encountered errors while trying to start a new project. Initially, I attributed it to my internet connection. Despite numerous attempts, I ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...