Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list comprehension containing enumerate equivalent in javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading