Please what is the equivalent in javascript of this python code
guessed_index = [
i for i, letter in enumerate(self.chosen_word)
if letter == self.guess
]
Both enumerate and list comprehension are not present in the ES6 equivalent, how to I combine both ideas into one
>Solution :
Focussing on the iterable/enumerate
part of your question rather than the specific task you’re performing: You can implement a JavaScript analogue of Python’s enumerate
using a generator function, and consume the resulting generator (which is a superset of an iterable) via for-of
(or manually if you prefer):
function* enumerate(it, start = 0) {
let index = start;
for (const value of it) {
yield [value, index++];
}
}
const word = "hello";
const guess = "l";
const guessed_indexes = [];
for (const [value, index] of enumerate(word)) {
if (value === guess) {
guessed_indexes.push(index);
}
}
console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);
Or you can write a specific generator function that does the task of finding matches:
function* matchingIndexes(word, guess) {
let index = 0;
for (const letter of word) {
if (letter === guess) {
yield index;
}
++index;
}
}
const word = "hello";
const guess = "l";
const guessed_indexes = [...matchingIndexes(word, guess)];
console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);