-3

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;
 }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40

2 Answers2

0

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

marekvospel
  • 412
  • 4
  • 9
0

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;
 }
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487