Recursion - Part 6 of 函数式编程
-
递归函数指自己调用自己直到被停止。
说起Recursion - 递归,你如果学过计算机科学, 那么一定会想起斐波那契。(1,1,2,3,5,8,...)function feibo(n) { if (n === 1) { return 1; } else if (n < 1) { return 0; } else { return feibo(n - 1) + feibo(n - 2); } }
其实在我的前端工作中,很少涉及斐波那契这样的算法题。那么需要前端需要递归吗?看看下面这个例子,
const categories = [ { id: "animals", parent: null }, { id: "mammals", parent: "animals" }, { id: "cats", parent: "mammals" }, { id: "dogs", parent: "mammals" }, { id: "aHuang", parent: "dogs" }, { id: "aMi", parent: "cats" }, { id: "aTu", parent: "dogs" }, { id: "aMao", parent: "cats" } ]; const makeTree = (categories, parent) => { let node = {}; //这个let很重要,它是block scoped的,也就是说下一次进入这个block,新的node被产生 categories .filter(c => c.parent === parent) .forEach(item => (node[item.id] = makeTree(categories, item.id))); return node; }; console.log(JSON.stringify(makeTree(categories, null), null, 2));
结果如下:
{ "animals": { "mammals": { "cats": { "aMi": {}, "aMao": {} }, "dogs": { "aHuang": {}, "aTu": {} } } } }
这里我们把一组数据转换成树状结构,按照父系相同归类。这个如果用for loop,代码一定很乱,makeTree这么写还是挺酷的吧?
总而言之,递归的作用是简化代码 - 这也是函数式编程的中心思想!