Search code examples
typescriptlet

Rewrite code without using let javascript


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;
 }

Solution

  • 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;
     }