• 纯函数&在树形结构中查找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>纯函数&在树形结构查找第四遍</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]) {
                console.log(1);
                obj[key] = func(...arguments);
              }
              return obj[key];
            };
          }
    
          let a = memorize(getArea);
          console.log(a(2));
          console.log(a(2));
          console.log(a(2));
          console.log(a(2));
          console.log(a(2));
    
          // 在树形结构中查找id
          let arr = [
            { id: 1, children: [{ id: 2, children: [{ id: 6 }] }] },
            { id: 3, children: [{ id: 4 }, { id: 5 }] }
          ];
          function serachInTree(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 = serachInTree(arr[key].children, id);
              }
            }
            return result;
          }
          let b = serachInTree(arr, 2);
          console.log(b);
        </script>
      </body>
    </html>

    树形结构中查找 id 出错,纯函数写对了

  • 相关阅读:
    C 扩展库
    访问nginx时验证密码
    关于redis闪退的案例
    查看进程的准确启动时间
    Ansible随笔8
    Ansible-随笔-7
    运维基本工作
    随笔-ansible-6
    随笔-ansible-5
    随笔-ansible-4
  • 原文地址:https://www.cnblogs.com/pengxiangchong/p/16123668.html
Copyright © 2020-2023  润新知