尝试创建 javascript 函数来搜索文本文件和 return 密钥对

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

假设我有一个名为 fruit.txt 的文件,其中包含以下格式的数据:

banana:yellow,apple:red,lime:green

我想创建一个名为 fruitcolor 的 javacript 函数,它将水果的名称作为其唯一参数,搜索 fruit.txt 文件和 returns 相应的水果颜色,如果没有找到水果 return 'not found'.

你可以read the file, split into chunks and move it to a Map让它更容易工作,像这样:

// 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.: 我假设文件内容不会改变。