I am creating a word generator like Awkwords that randomly picks a letter from a labelled array and puts it in a sequence.
I am currently just having the label be the first item of its array. Here's a simple version:
let sequence = 'CVC'
let word = ''
let consonants = ['C', 'b', 'c', 'd',]
let vowels = ['V', 'a', 'e', 'i',]
let lists = [consonants, vowels]
for (letter of sequence) {
for (list of lists) {
if (list[0] === letter) {
pick random letter out of the list other than its first value and add it to the word
}
}
}
I'm almost brand new to programming in general so I have no idea if this is the way I should be doing this. Is there a more efficient way to label an array?
There will be a max of 26 lists (one for each letter) and the items within them will change depending on what the user inputs.
One way to get something like a "labeled array" is to use a javascript object. Here you could use the letters as keys (or properties) and the associated list as the value. This would also save you looping through the lists to search for the desired letter.
Try something like below:
let sequence = "CVC";
let word = "";
let patterns = {
C: ["b", "c", "d"],
V: ["a", "e", "i"]
};
for (letter of sequence) {
// do something here with patterns[letter]
console.log(patterns[letter])
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments