user647314
user647314

Reputation: 327

JS recursion returns undefined

I would like to get back the result as a return value from the recursion, but I get 'undefined'. I read through all the related solutions (see ***) here, but somehow my example doesn't work. If I'm using a global variable then I can get the result otherwise the return values is 'undefined'.

https://stackblitz.com/edit/typescript-1b2ktw

export interface Needle {
  needles: Needle[];
  text: string;
}

export const Needles: Needle[] = [
  {
    text: 'root',
    needles: [
      {
        text: 'a',
        needles: [
          { text: 'a1', needles: null },
          { text: 'a2', needles: null },
        ],
      },
      { text: 'b', needles: null },
    ],
  },
];

let result;

function findNeedle(needles: Needle[], key: string, value: string): any {
  needles.forEach((x) => {
    if (x[key] === value) {
      // return x as Needle; // doesnt work
      result = x; // works just ugly
    }
    if (x.needles) {
      needles = x.needles;
      // return findNeedle(needles, key, value); solution *** like this doesnt work also
      findNeedle(needles, key, value);
    }
  });
}

console.clear();
let x = findNeedle(Needles, 'text', 'a1');
console.log('x:', x, 'result', result);
--- CONSOLE
Console was cleared
x:undefined, result {text: "a1", needles: null}

How can I fix this to get back the result in return value ?

Thanks in advance.

Csaba

Upvotes: 1

Views: 50

Answers (2)

trincot
trincot

Reputation: 350272

Don't use forEach, but a for..of loop. That way you can return something without being trapped within a callback function.

function findNeedle(needles: Needle[], key: string, value: string): any {
  for (let x of needles) {
    if (x[key] === value) return x;
    if (x.needles) {
      result = findNeedle(x.needles, key, value);
      if (result) return result;
    }
  }
}

Upvotes: 1

Nathan Wiles
Nathan Wiles

Reputation: 926

x is undefined because findNeedle() doesn't return a result, it assigns one instead to the result variable.

Upvotes: 0

Related Questions