Home > front end >  How to have a string that change it value over time based in another string?
How to have a string that change it value over time based in another string?

Time:01-19

There is any way to make a code that pick a random between these values:

let initialString = "single result:\nfoo||bar||anything||something"
let endString
setInterval(()=>{
    endString = // do some stuff do define its value
    console.log(endString)
},1000)

CodePudding user response:

As @barmar suggested in his comment, You can simply achieve that by splitting a initialString into an array with the help of Array.split() method and then find the random element from that array and print it out.

Live Demo :

let initialString = "single result:\nfoo||bar||anything||something";

const arrString = initialString.split('||');

function getRandomItem(arr) {
    // get random index value
    const randomIndex = Math.floor(Math.random() * arr.length);
    // get random item
    const endString = arr[randomIndex];
    return endString;
}

console.log(getRandomItem(arrString));

CodePudding user response:

I've found out that for my application is better to put the possibilities between parentheses to separate then from the parts of the string that don't need to be touched

let initialString = "single result:\n(foo|bar|anything|something)"
let endString
let stringChangeInterval = setInterval(() => {
    let validatedPairs = []
    for(let i = 0; i < initialString.length; i  ){
        if(initialString[i] != "(") continue
        for(let j = i 1; j < initialString.length; j  ){
            if(initialString[j] != ")") continue
            validatedPairs.push([i, j])
            i = j
            break
        }
    }
    endString = initialString
    for(let i = validatedPairs.length-1; i >= 0; i--){
        let possibilities =  initialString.substring(validatedPairs[i][0] 1, validatedPairs[i][1]).split('|')
        if(possibilities.length ===  1) continue
        let choosenPossibilty = randomFromArray(possibilities)
        endString = endString.replace(endString.substring(validatedPairs[i][0], validatedPairs[i][1] 1), choosenPossibilty)
    }
    console.log(endString)
}, 1000);

function randomFromArray(array){
    return array[Math.floor(Math.random() * array.length)]
}
  • Related