javascript - recursion method returning undefined

3338 views javascript
1

I'm writing something where you can generate a random number, and it checks if its in an array, if it is, it generates a different one until a unique is found and adds that into the array and so on. For some reason it returns undefined after recursively running itself. why?

returning 2 index.js:26 retrieved 2

index.js:26 found a duplicate 2

index.js:26 returning 1

index.js:26 retrieved undefined

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const MAX = 3;

class Clickity extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numbers: []
    }
  }

  generateRand = () => {
    // generate a random number 1 - MAX (3)
    let rand = Math.floor(Math.random() * MAX + 1);
    let { numbers } = this.state;

    // if length of array is equal to max return 0
    if (numbers.length === MAX) return 0;

    // check if generated number is in array
    if (numbers.includes(rand)) {
      console.log(`found a duplicate ${rand}`)
      // recursively run method
      this.generateRand();
    } else {
      // return the random number
      console.log(`returning ${rand}`)
      return rand;
    }
  }

  addNewNumber = () => {
    let id = this.generateRand();
    console.log(`retrieved ${id}`)
    let { numbers } = this.state;
    numbers.push(id);
    this.setState({ numbers });
  }

  render() {
    return (
      <div>
        <a onClick={() => this.addNewNumber()}>Generate unique number</a>
        <ul>{this.state.numbers.map((num) => <li>{num}</li>)}</ul>
      </div>
    )
  }
}

function App() {
  return (
    <Clickity />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

answered question

2 Answers

12

You don't return this.generateRand()

posted this
12

 `return` is missing when you re calling `this.generateRand()` in recursion here.



 if (numbers.includes(rand)) {
          console.log(`found a duplicate ${rand}`)
          // recursively run method
          this.generateRand();
        }




 generateRand = () => {
    // generate a random number 1 - MAX (3)
    let rand = Math.floor(Math.random() * MAX + 1);
    let { numbers } = this.state;

    // if length of array is equal to max return 0
    if (numbers.length === MAX) return 0;

    // check if generated number is in array
    if (numbers.includes(rand)) {
      console.log(`found a duplicate ${rand}`)
      // recursively run method
      return this.generateRand();
    } else {
      // return the random number
      console.log(`returning ${rand}`)
      return rand;
    }
  }

posted this

Have an answer?

JD

Please login first before posting an answer.