0

i'm new to generator function and trying execute while loop inside it.

export function* findRandomData(list, name) {
  let searchList = true;
  const formattedName = name
    .replace(new RegExp('_', 'g'), ' ')
    .toLowerCase();

  const indexesToSearch = [];
  for (let i = 0; i < list.length; i++) {
    indexesToSearch.push(i);
  }

  let viableId;
  // Search through results
  while (searchList) {
    // If there are no results left then finish
    if (indexesToSearch.length === 0) {
      searchList = false;
      throw new Error('Could not find id');
    }

    // Find a random number that has not been selected already, then remove
    const randomPosition = Math.floor(Math.random() * indexesToSearch.length);
    indexesToSearch.splice(randomPosition, 1);

    let title = list[randomPosition].title;
    viableId = list[randomPosition].id;

    const eligible = yield call(
      isEligibleVideo,
      title,
      formattedName,
      viableId
    );

    if (eligible) {
      searchList = false;
    }
  }

  return viableId;
}

but it return null even though the while loop have not completed for search.

const data = yield call(findRandomData, resp['res'], name);

Error Error: Could not find id at findRandomData

what is it that i'm doing wrong

Barmar
  • 741,623
  • 53
  • 500
  • 612
Nikhil Shrestha
  • 1,210
  • 1
  • 11
  • 18
  • I notice you're assigning to `eligible` but testing `eligibleVideo` — are those meant to be the same? – deltab Jun 18 '20 at 04:19
  • yeah its eligible, edit mistake. `eligible` returns the value. i tried with normal function it works but not in generator function – Nikhil Shrestha Jun 18 '20 at 04:21
  • You're not accessing any of the values of `indexesToSearch`. – deltab Jun 18 '20 at 04:29
  • `indexesToSearch` is for checking the position in the list once the position is randomly generated its been removed so that it wont recheck the same data twice – Nikhil Shrestha Jun 18 '20 at 04:39
  • I thought as much, but the way you're currently using it after it's filled is only to get its length and to remove a random element: something's missing. Consider what happens if `randomPosition` is assigned 3 twice, for instance. – deltab Jun 18 '20 at 04:46

1 Answers1

0

Try to give a value to viableId variable when you declare it, for example : let viableId = ""; // if your variable will receive a string value

Or give it a number value (generally people uses 0) if you're working with numbers.

Adel A
  • 46
  • 2