Transforming generator into a regular function

I need to refactor some code for a project, but we've decided internally not to use generators. I found this code snippet that looks unnecessary to me since it doesn't seem to require a generator at all. How can I convert it into a regular function without using generators (as far as I know, there are no async operations)?

Just to clarify, I'm looking to remove generators from this specific piece of code.

Code:

const getResults = (totalData) => {
    const combinations = totalData.reduce((a, b) => a * b.length, 1); 
    return function() { 
        for (let i = 0; i < combinations; i++) { 
            yield createSolution(i, totalData); 
        } 
        return null; 
    }
}

This is how the function is called:

const result = getResults(obj.elementsInObj);

for (let data of result()) {
    const resolve = validateData(data, obj.elementsInObj);
    if (resolve) {
        return resolve;
    }
}

Answer №1

To simplify the code, you can eliminate the asterisk and yield operator. Instead, create an internal array to store the solutions. Afterwards, return that array and iterate over it.

const collectResults = (totalData) => {
  const combinations = totalData.reduce((a, b) => a * b.length, 1),
        arr = [];
  for (let i = 0; i < combinations; i++) arr.push(createSolution(i, totalData));
  return arr;
}

const results = collectResults(obj.elementsInObj);
for (let data of results) {
  const resolve = validateData(data, obj.elementsInObj)
  if (resolve) return resolve
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The data does not match the expected outcome after the loop

It seems like I might be overlooking something obvious here, as I've spent a considerable amount of time testing this out and still can't seem to figure out what's going wrong. The goal is to iterate through each item in an array (dataArray ...

Animating three-dimensional objects using Three.js in real-time

I have been working with three.js and have successfully animated some objects using the animate() function. Here's a snippet of my code: function animate(){ object.position.z++; } The issue I'm facing is that this function is called every r ...

"ReactJS error: Unable to upload file due to a 400

Every time I attempt to upload a file, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 404". I'm puzzled as to why this is happening. Here's the section of my code that seems to be causing the issue. ...

Encountering an issue when using both the Google Maps API and Google URL Shortener API within the same program

Recently, I developed a program that involves passing data to an iframe through a URL. However, due to the limitation of Internet Explorer supporting only 2083 characters in a URL, I decided to use the Google URL Shorten API to shorten the URL before sendi ...

Tips for avoiding problems with quoting and using apostrophes in a JavaScript function inside a tag in a JSP file

Within my JSP, I have a string value stored in ${state.status.code} that I need to pass to a JavaScript function when a table element is clicked using onClick to trigger the showStatus function. Here is how I have attempted to achieve this: <c:set var= ...

When running "npx react-native init client" on Android, the command fails due to the error message stating that tools.jar could not be found. This issue occurs specifically with React

Device: Windows 10 NodeJS Version: v13.8.0 React Native Version: 0.62.2 React Version: "16.11.0" The issue persists even with the typescript template. Upon executing the command npm run android, I encountered the following logs: info Running je ...

Issue with Javascript function not triggering on Django dropdown selection change event

I have a question. I have a JS function that I downloaded from the internet and is being used in a Django project. In my template.html file, I have a <select class="select_filter" onchange="myFunc(this.value);"></select>. Ad ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

Incorporating sweetalert2 with the latest Bootstrap 4 framework

I am currently utilizing sweetAlert2 and attempting to integrate bootstrap 4 for button styling by implementing the following properties: buttonsStyling: false, confirmButtonClass: 'btn btn-primary btn-lg', cancelButtonClass: 'btn btn-lg&ap ...

When importing modules in node.js, the presence of a function can overwrite another function even if it

Within this code snippet, I am utilizing Express.js. //index.js app.use('/',routes()); //app/routes.js module.exports = function() { express = require('express'); const loggedUserProfileController = require('../controller ...

Update your code to use the fetch API instead of axios

Looking to switch my axios post call to a fetch call: export async function createFriend ({ let myData = new FormData() myData.append('name', name) myData.append('age', age) const response = await axios.post('/myApi/friends ...

Localization of date picker in material-table(Material UI)

Does anyone have experience with localizing the date picker in material-table (Material UI)? The date picker is specifically used for filtering in this scenario. import React from 'react'; import MaterialTable from 'material-table'; fu ...

The addition of meshes in real-time leads to a decrease in control responsiveness

I'm currently working on creating a 3D map using Three.js. My process involves building the geometry and texture with images of size 256x256 pixels, then constructing a THREE.Mesh to add to the scene upon completion. However, I've noticed that ...

Angular, delete any item from the scope that has a matching key value

One of the challenges I am facing is removing items from an array with the same key value of skillId when a button in the repeat is clicked. Here's the code snippet I have worked on: $scope.deleteSkill = function(skill) { for (var i=0; i<$ ...

Is there a way to modify the Java class name to consist of two separate words?

(Edited) I am completely new to android app development. My question is: How can I rename a java class with two words instead of one? My main menu consists of 3 options, each linked to a java class: public class Menu extends ListActivity{ String cla ...

React and Redux Toolkit collaborated to create a seamless shared state management system,

Currently, I am developing a simple application to experiment with Redux Toolkit alongside React. Despite being able to view the object in the Redux Chrome tab, I am facing difficulties accessing it using React hooks within components. The code for my sli ...

Remove files from the server using an AJAX request

I am attempting to delete files on the SERVER using JavaScript, and I have already consulted the advice provided in this JavaScript file deletion thread My current JavaScript code looks like this: deleteFile = function() { return $.ajax({ url: "de ...

Switch the checked status of an input dynamically using jQuery function

It seems like I might be overlooking something quite obvious, but I can't figure out why this jquery function is behaving inconsistently. HTML: <label id="income_this_tax_year"> <div class="left"> <p>Have you had Self-Employm ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...

Upon reaching a specific milestone on the page, automatically scroll to the designated anchor point

Here's the deal: I plan to showcase 4 divs on my page. Each div will have a specific height (around 1500px) but will span the full width of the screen. To add some flair, each div will be a different color. My goal is for JavaScript to kick in once ...