0

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

1 Answer 1

3

You don't return this.generateRand()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.