JavaScript食谱搜索引擎项目咨询:结果不全及代码优化建议
食谱搜索引擎代码优化请求
我做的第一个JavaScript项目是食谱搜索引擎,目前存在以下问题:
- 无法输出全部匹配结果
- 没有错误提示机制
- 部分代码测试能运行,但反馈称未检查完整字符串
项目任务要求:
- 创建
searchRecipes函数,接收所有食谱数据及搜索条件对象,返回匹配的食谱数组; - 创建
printRecipes函数,接收食谱数组,输出食谱数量及包含名称、作者等信息的食谱列表。
原项目代码
'use strict'; const cakeRecipes = require("./cake-recipes.json"); console.log(cakeRecipes[0]); // If you're ready to test: uncomment the code below. // printRecipes(searchRecipes(cakeRecipes, {})); // 162 // printRecipes(searchRecipes(cakeRecipes, { ingredients: ["carrot"] })); // 3 // printRecipes(searchRecipes(cakeRecipes, { authors: ["Good food"] })); // 32 // printRecipes(searchRecipes(cakeRecipes, { searchTerms: "christmas simple" })); // 5 // printRecipes( // searchRecipes(cakeRecipes, { // ingredients: ["nuts"], // searchTerms: "christmas simple", // }) // ); // 2 // printRecipes( // searchRecipes(cakeRecipes, { // authors: ["best", "cook"], // ingredients: ["syrup"], // searchTerms: "brunch pancakes", // }) // ); // 2 //***********part 1: declare function search recipes****// //Use the JSON.stringify method in this function converting the arrays to a string. This by every part of searching to make it possible to search. const search = ['']; const result = ['']; function compareArraysWithJSONStringify (arraySearch, arrayResult) { return JSON.stringify(arraySearch) === JSON.stringify(arrayResult); } let compareWithJSONStringify = compareArraysWithJSONStringify (search, result); //Create a function called searchRecipes that takes all recipes and an object with search criteria.//This function should return an array of recipes that match the search parameters.// method filter() to create new array that filter recipes based on parameters. Push method to add a new item. Returns new array. //set it to lower case to make it case insensitive // Creating a function that returns an array of recipes that match the search parameters. Check first if the element is there in the JSON String. const searchRecipes = (search,recipe) => { const filterResult = []; // declare empty array. function filterItems(search, recipe) { return search.filter((el) => el.toLowerCase().includes(recipe.toLowerCase().filterResult.push((el)))) } }; //************** part 2:ingredients***************// // First use the JSON.stringify method to convert arrays to string in order to do search matching. //set it to lower case to make it case insensitive const filterIngredients = (recipe, search) => { recipe = JSON.stringify(recipe).toLowerCase() search = search.map((element) => element.toLowerCase()) const filterResult = searchItemInRecipe(search, recipe)// have to start searching const result = compareSearchWithResult(search, filterResult) // compare the searching result return result } //***************part 3:author***************// // First use the JSON.stringify method to convert arrays to string in order to do search matching. const searchForAuthor = (recipe, search) => { recipe = JSON.stringify(recipe).toLowerCase() search = search.map((el) => el.toLowerCase()) let result = false if ( search.filter((el) => { if (recipe.includes(el)) { result = true } }) ); return result } //************part 4: searchterms*********// const searchForSearchTerms = (recipe, search) => { recipe = recipe.Name.concat(recipe.Description).toLowerCase() search = search.toLowerCase() // search = search.split(" ") const filterResult = searchItemInRecipe(search, recipe) const result = compareSearchWithResult(search, filterResult) return result } // step for searching result recipes and ingredients const filterRecipes = (recipes, search) => { const result = [] recipes.forEach((recipe) => { const ingredientsInRecipe = recipe.Ingredients const ingrendientsInSearch = search.ingredients if (ingrendientsInSearch) { if (!searchForIngredients(ingredientsInRecipe, ingrendientsInSearch)) return } //search for author. Check if all is controlled works. Create new array for result using method push() , then return result const authorFromRecipe = recipe.Author const authorsFromSearch = search.authors if (authorsFromSearch) { if (!searchForAuthor(authorFromRecipe, authorsFromSearch)) return. } const searchTerms = search.searchTerms if (searchTerms) { if (!searchForSearchTerms(recipe, searchTerms)) return } result.push(recipe) }) return result } // Creating a function that takes an array of recipes const printRecipes = (foundRecipes) => { const amountOfRecipes = recipes.length let recipeCount = 1 console.log( `Number of matched recipes are ${foundRecipes} ` ); //Log the found recipes recipes.forEach((recipe) => { const name = recipe.Name const author = recipe.Author const description = recipe.Description const ingredients = recipe.Ingredients // print out a list of recipes, displaying the name, author(s), description foundRecipes.forEach((recipe) => { console.log(`\nRecipe ${recipeCount++}:`) console.log(`${name}`) console.log(`By: ${author}`) console.log("\nAbout this recipe:") console.log(description) console.log("\nIngredients:\n") ingredients.forEach((ingredient) => console.log(` * ${ingredient}`)) console.log("\n______________________________________________\n"); }); }) } //Paramenters that are used in search const searchParams = { authors: ["best", "cook"], ingredients: ["syrup"], searchTerms: "brunch pancakes", }
核心问题分析与优化方案
1. 修复searchRecipes函数逻辑
原函数参数顺序颠倒、内部逻辑未执行,重新实现为调用核心过滤逻辑:
const searchRecipes = (recipes, searchCriteria) => { // 参数校验:添加错误提示 if (!Array.isArray(recipes)) { console.error("错误:recipes必须是数组格式"); return []; } if (typeof searchCriteria !== 'object' || searchCriteria === null) { console.error("错误:搜索条件必须是对象格式"); return []; } // 空搜索条件返回全部食谱 if (!Object.keys(searchCriteria).length) return [...recipes]; return filterRecipes(recipes, searchCriteria); };
2. 修复食材搜索逻辑(避免JSON.stringify弊端)
原代码用JSON.stringify会导致部分匹配错误(比如"carrot"匹配"carrots"),改为逐食材完整匹配:
const searchForIngredients = (recipeIngredients, searchIngredients) => { const lowerRecipeIngs = recipeIngredients.map(ing => ing.toLowerCase().trim()); return searchIngredients.every(ing => { const targetIng = ing.toLowerCase().trim(); return lowerRecipeIngs.some(recipeIng => recipeIng.includes(targetIng)); }); };
3. 修复作者搜索逻辑(支持多作者匹配)
原函数filter后未判断结果,改为检查是否有任意作者匹配:
const searchForAuthor = (recipeAuthor, searchAuthors) => { const lowerRecipeAuthor = recipeAuthor.toLowerCase().trim(); return searchAuthors.some(author => { const targetAuthor = author.toLowerCase().trim(); return lowerRecipeAuthor.includes(targetAuthor); }); };
4. 修复搜索词逻辑(支持多关键词全匹配)
原函数未正确处理多关键词,改为要求所有搜索词都在名称/描述中存在:
const searchForSearchTerms = (recipe, searchTerms) => { const fullText = `${recipe.Name} ${recipe.Description}`.toLowerCase().trim(); const terms = searchTerms.toLowerCase().trim().split(/\s+/); // 按任意空格分割关键词 return terms.every(term => fullText.includes(term)); };
5. 修复printRecipes函数变量与循环错误
原函数使用未定义变量、嵌套重复循环,重新实现:
const printRecipes = (foundRecipes) => { // 空结果提示 if (!foundRecipes.length) { console.log("未找到匹配的食谱"); return; } console.log(`匹配的食谱数量:${foundRecipes.length}`); let recipeCount = 1; foundRecipes.forEach((recipe) => { console.log(`\n食谱 ${recipeCount++}:`); console.log(`名称:${recipe.Name}`); console.log(`作者:${recipe.Author}`); console.log("\n食谱介绍:"); console.log(recipe.Description); console.log("\n食材列表:"); recipe.Ingredients.forEach((ingredient) => console.log(` * ${ingredient}`)); console.log("\n----------------------------------------------\n"); }); };
6. 统一函数命名与修复调用错误
原代码存在函数名不统一问题,修复filterRecipes中的调用错误:
const filterRecipes = (recipes, search) => { const result = []; recipes.forEach((recipe) => { // 食材检查 if (search.ingredients) { if (!searchForIngredients(recipe.Ingredients, search.ingredients)) return; } // 作者检查 if (search.authors) { if (!searchForAuthor(recipe.Author, search.authors)) return; } // 搜索词检查 if (search.searchTerms) { if (!searchForSearchTerms(recipe, search.searchTerms)) return; } result.push(recipe); }); return result; };
7. 测试验证
取消注释测试代码,验证所有用例是否符合预期结果:
printRecipes(searchRecipes(cakeRecipes, {})); // 162 printRecipes(searchRecipes(cakeRecipes, { ingredients: ["carrot"] })); // 3 printRecipes(searchRecipes(cakeRecipes, { authors: ["Good food"] })); // 32 printRecipes(searchRecipes(cakeRecipes, { searchTerms: "christmas simple" })); // 5 printRecipes( searchRecipes(cakeRecipes, { ingredients: ["nuts"], searchTerms: "christmas simple", }) ); // 2 printRecipes( searchRecipes(cakeRecipes, { authors: ["best", "cook"], ingredients: ["syrup"], searchTerms: "brunch pancakes", }) ); // 2
内容的提问来源于stack exchange,提问作者Yass
相关产品推荐
相关产品推荐

