Skip to content
Advertisement

Trying to create javascript function to search text file and return key pairing

So lets say I have a file called fruit.txt that contains the following data in this format:

banana:yellow,apple:red,lime:green

I want to create a javacript function called fruitcolor that takes the name of the fruit as its only parameter, searches the fruit.txt file and returns the corresponding color of the fruit, if no fruit is found return ‘not found’.

Advertisement

Answer

you could read the file, split into chunks and move it to a Map to make it easier to work it, something like this:

// read the file in js (plenty of tutorials over there)
const fileContent = 'banana:yellow,apple:red,lime:green';
const map = new Map(fileContent.split(',').map(group => group.split(':')));

function fruitcolor(fruitName) {
    return map.has(fruitName) ? map.get(fruitName) : 'not found';
}

P.S.: I am assuming that the file content won’t change.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement