Home > OS >  How can I store data for a line of numbers logic?
How can I store data for a line of numbers logic?

Time:11-29

So basically I have this code in a discord bot that'll appear in general-chat, and it says "Guess the correct number from 1-10" and it's a random number each time.

So, what this code is supposed to do, is every time a incorrect number is guessed, it'll update the "line of numbers" to make it slightly obvious what the number is.

Example: They guess numbers 1, 4, 5, and 7.

The embed should look like

1 _ _ 4 5 _ 7 _ _ _, but what's happening is that it doesn't save every single guess, so it'll only update the embed with the last guessed number

_ _ _ _ _ _ 7 _ _ _ ( like this ), so how can I store all of the incorrect guessed answers, to work like how I want it to?

code: https://www.toptal.com/developers/hastebin/rowexaketi.js

CodePudding user response:

You can have an array with all the guesses that go wrong. Create that array in a scope that is visible for your function, and than you use the includes method to check if that number was tried before.

Example:

const triedNumbers = [5,9,10]; // Start it as empty array, this is just for testing
const possibleValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
// Use reduce instead of mapping to transform the array into a string later
const finalString = possibleValues.reduce((accumulated, current) => {
    if(triedNumbers.includes(current)) return `${accumulated}${current}`;
    return `${accumulated}_`;
}, '');

console.log(finalString);

Link to reduce docs.

A couple of suggestions: change the variables names of your code, you have multiple indexes: index, index3, index4, which makes really difficult to read and understand how your code is working. Also, if you are creating variables that are not going to be mutated later, use const instead of let.

  • Related