纯函数&根据id在树形结构中查找
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>纯函数&在树形结构查id第三遍</title> </head> <body> <script> // 纯函数 function getArea(r) { return Math.PI * r * r; } function memorize(func) { let obj = {}; return function () { let key = JSON.stringify([...arguments]); if (!obj[key]) { obj[key] = func(arguments); } return obj[key]; }; } // 搞混了 let a = memorize(getArea); console.log(a(5)); function searchInTree(arr, id) { let result = null; if (!arr) { return; } for (let key in arr) { if (result !== null) { break; } if (arr[key].id === id) { result = arr[key]; break; } else if (arr[key].children && arr[key].children.length > 0) { result = searchInTree(arr[key].children, id); } } return result; } </script> </body> </html>
再写三遍,搞混了~~