Home > Software design >  Rewrite code without using let javascript
Rewrite code without using let javascript

Time:05-30

Assuming reassignment of variable can lead to bugs what hard to debug, I am looking for options not to use let in this example. Please advice.

function getNodeById<F extends ISomeOptions>(
   optionsList: F[],
   nodeId: string): F | null {

   let result: ISomeOptions | null = null;

   optionsList.forEach((node) => {
     if (node.id === nodeId) {
       return (result = node);
     }

     if (
       Array.isArray(node.children) &&
       getNodeById(node.children, nodeId)
     ) {
       return (result = getNodeById(node.children, nodeId));
     }

     return null;
   });

   return result;
 }

CodePudding user response:

You want a simple loop which you can immediately return from instead of forEach:

function getNodeById<F extends ISomeOptions>(
   optionsList: F[],
   nodeId: string): F | null {

   for (const node of optionsList) {
     if (node.id === nodeId) {
       return node;
     }

     if (Array.isArray(node.children)) {
       const node1 = getNodeById(node.children, nodeId);
       if (node1) {
         return node1;
       }
     }
   }

   return null;
 }

CodePudding user response:

You can use Array.find

function getNodeById<F extends ISomeOptions>(
   optionsList: F[],
   nodeId: string): F | null {

   return optionsList.find((node) => {
      if (node.id === nodeId) return node
      if (Array.isArray(node.children) {
         // getNodeById is a recursive function, so it could be expensive to run it twice.
         let child = getNodeById(node.children, nodeId)
         if (child) return child
      }
   });

   return result;
 }

  • Related