如何简化这段多层嵌套循环的重复函数调用代码?
简化嵌套循环的两种实现方式
原代码本质是从currentSolution出发,连续调用9次findSolutionsWithOneMorePiece,最终收集第9次调用后非空的结果。重复的嵌套逻辑完全可以用递归或迭代循环简化,以下是具体实现:
方案一:递归实现
把重复调用逻辑封装成递归函数,通过控制剩余调用次数终止递归:
const solutions: Solution[] = []; // 递归函数:currentSols为当前待处理的解决方案列表,remaining为剩余需调用的次数 function collectSolutions(currentSols: Solution[], remaining: number) { if (remaining === 0) { // 剩余次数为0时,收集非空解决方案 currentSols.forEach(sol => { if (sol.length) solutions.push(sol); }); return; } // 合并当前所有解决方案的调用结果 const nextSols = currentSols.flatMap(sol => findSolutionsWithOneMorePiece({ currentSolution: sol, pieceSet: currentPieceSet }) ); // 递归调用,剩余次数减1 collectSolutions(nextSols, remaining - 1); } // 初始调用:从[currentSolution]开始,需调用9次 collectSolutions([currentSolution], 9); console.log(solutions);
方案二:迭代循环实现
如果对递归不熟悉,用普通循环更直观:
let currentSols: Solution[] = [currentSolution]; // 循环9次,每次更新当前解决方案列表 for (let i = 0; i < 9; i++) { currentSols = currentSols.flatMap(sol => findSolutionsWithOneMorePiece({ currentSolution: sol, pieceSet: currentPieceSet }) ); } // 收集最终非空的解决方案 const solutions: Solution[] = currentSols.filter(sol => sol.length); console.log(solutions);
关键说明
- 两种方案都用
flatMap合并每次调用后的结果数组,替代手动嵌套循环。 - 严格遵循原代码逻辑:仅在第9次调用后收集非空结果。
- 迭代版本适合担心递归栈溢出的场景(9次递归无栈溢出风险),递归版本更贴合原代码的嵌套逻辑结构。
内容的提问来源于stack exchange,提问作者Morgan
相关产品推荐
相关产品推荐

