Home > Software engineering >  JS: does recursive require a `return`?
JS: does recursive require a `return`?

Time:08-31

I know the best way to handle this would be in a loop but how would I do this in a recursive manner? When I call this.findName again, do I have to return after it? Or do I exclude the 'return ?

names = [ // 50  names in array ]

findName() {
   
     if (names[0]) {
        if (names[0].includes("XX") {
            names.shift();
            this.findName();
            return;
        }
     } else {
       return "DONE!"
     }

}

CodePudding user response:

Beside mutating the original data, you need another else part or reorder the structure by taking the exit condition first and then check if the string contains a wanted pattern and return this or return the result of the recursive call.

const
    names = ['jane', 'bob', 'mary', 'klaus', 'sue', 'fred'];

function findName() {   
    if (!names[0]) return "DONE!";
    if (names[0].includes("ue")) return names[0];
    names.shift();
    return findName();
}

console.log(findName());

Nonmutating approach

function findName(names, pattern) {   
    if (!names.length) return;
    if (names[0].includes(pattern)) return names[0];
    return findName(names.slice(1), pattern);
}

console.log(findName(['jane', 'bob', 'mary', 'klaus', 'sue', 'fred'], 'xx'));
console.log(findName(['jane', 'bob', 'mary', 'klaus', 'sue', 'fred'], 'ue'));

CodePudding user response:

In order to do recursion you must have a return on the recursion routine. It's not clear but I think what you are trying to do is go through the array until you find XX. I modified your code below:

The answer above from Nina is a better answer. When you do recursion, think of the stopping condition and how you reduce the problem with each call to the routine

let names = ["a", "b","XX", "cc"]

function findName() {
  console.log(names)

  if (names[0]) {
    if (!names[0].includes("XX")) {
      names.shift();
      return findName();
    } else {
      return "DONE!"
    }
  } else {
    return "done2"
  }

}

console.log(findName())

  • Related