What is the correct way to iterate through an object, evaluate three properties, and then push them into an array?

I am tasked with creating a function called runOnRange that will populate a new array based on the properties of an object. The object contains three properties: start, end, and step. The goal is to push specific numbers into the array according to these properties and then return the array.

As a beginner, I need to stick to basic techniques like loops and conditionals.

Here are some examples that illustrate what is needed:

runOnRange({start: 10, end: 17, step: 3})

// => 10 // => 13 // => 16

runOnRange({start: -6, end: -4})

// => -6 // => -5 // => -4

runOnRange({start: 12, end: 12})

// nothing should be console.logged in this case!

runOnRange({start: 23, end: 26, step: -1})

// nothing should be console.logged in this case!

runOnRange({start: 26, end: 24, step: -1})

// => 26 // => 25 // => 24

runOnRange({start: 23, end: 26, step: 0})

// nothing should be console.logged in this case!

This is the current code implementation:

function runOnRange (object) {
    var arrNew = []
    var start = object.start
    var end = object.end
    var step = object.step

    //Case 1: steps between start and end range
    if(start + step <= end && start + step >= start) {
        for (var i = start; i <= end; i = i + step) {
            arrNew[i]=i;
        }
    }

    //Case 2: steps not set, defaulting to increment by one
    if (step == undefined) {
        step == 1;
        if(start + step <= end && start + step >= start) {
            for (var i = start; i <= end; i = i + step) {
                arrNew[i]=i
            }
        }
    }
    return arrNew
}

When running

runOnRange({start: 10, end: 17, step: 3})

the output in the console shows

(17) [empty × 10, 10, empty × 2, 13, empty × 2, 16] 

indicating there is at least one error.

Executing

runOnRange({start: -6, end: -4})

results in an empty array, whereas it should increase the steps parameter by one.

Where have I made mistakes?

Answer №1

To prevent the creation of a sparse array, it is important to increment the value of i in arrNew[i] by just one, instead of by a certain step - although utilizing push would be more convenient.

For an even simpler approach, I recommend using a basic while loop with the option to specify a step parameter that defaults to 1:

function generateNumberRange ({ start, end, step = 1 }) {
  const arr = [];
  if (step === 0) { // handling a unique case...
    return arr;
  }
  let currNum = start;
  while (start < end ? (currNum < end) : (currNum > end)) {
    arr.push(currNum);
    currNum += step;
  }
  return arr;
}

console.log(generateNumberRange({start: 10, end: 17, step: 3}));
console.log(generateNumberRange({start: 12, end: 12}));
console.log(generateNumberRange({start: 26, end: 24, step: -1}));

Answer №2

Well, this explanation does go on a bit to cover all scenarios. But the key points are

  • Use array.push instead of an index
  • Avoid unnecessary repetition; set step as 1 if it's undefined
  • Exit early if step is zero
  • Different conditions needed for step being >0 or <0.

function runOnRange(obj){
   var start = obj.start;
   var end = obj.end;
   var step = (obj.step == undefined) ? 1 : obj.step;
   var arrNew = [];
   if(step == 0) return arrNew;
   
   if((step>0 && start + step <= end && start + step >= start) || (step<0 && start + step >= end && start + step <= start)) {
        for (var i = start; (step>0 && i <= end) || (step<0 && i>=end); i = i + step) {
            arrNew.push(i);
        }
    }
    return arrNew;
}

console.log(runOnRange({start: 10, end: 17, step: 3}))
// => 10 // => 13 // => 16

console.log(runOnRange({start: -6, end: -4}))
// => -6 // => -5 // => -4

console.log(runOnRange({start: 12, end: 12}))
// nothing should be console.logged in this case!

console.log(runOnRange({start: 23, end: 26, step: -1}))
// nothing should be console.logged in this case!

console.log(runOnRange({start: 26, end: 24, step: -1}))
// => 26 // => 25 // => 24

console.log(runOnRange({start: 23, end: 26, step: 0}))
// nothing should be console.logged in this case!

Answer №3

Alright,

I believe I have found a solution in this code snippet. It may not be the most elegant or efficient, but it seems to get the job done for now.

function runOnRange (object) {
    var arrNew = []
    var start = object.start
    var end = object.end
    var step = object.step

    //Case 0: handling when step is 0
    if (step === 0) {
        return arrNew
    }

    //Case 1a: steps between start and end range, where start is smaller than end
    if(start + step <= end && start + step >= start) {
        for (var i = start; i <= end; i = i + step) {
            arrNew.push(i)
        }
    }

    //Case 1b: steps between start and end range, where start is higher than end
    if(start + step >= end && start + step <= start) {
        for (var i = start; i >= end; i = i + step) {
            arrNew.push(i)
        }
    }

    //Case 2: default case where step is not set, increments by one
    if (step == undefined) {
        step == 1;
        if(start + step <= end && start + step >= start) {
            for (var i = start; i <= end; i = i + step) {
                arrNew[i]=i
            }
        }
    }
    return arrNew
}

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

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

Recognize when the DOM undergoes modifications

After taking Matt's suggestion, I have made changes to the .ready() call. In my workflow, I utilize jQuery to set up certain configurations like this: $(function () { $('.myThing').each(function() { ... configuring happens he ...

Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario. I am exploring various small use cases of differ ...

How to Retrieve Information from an Array in VueJS

At the moment, the data being displayed on my page is an array, as shown in the snippet below: https://i.stack.imgur.com/zAvrc.png However, I only want to retrieve or display the project names. This is all I have at the moment: fetch(context,id){ ...

EJS variable not detected by Visual Studio IDE in JavaScript file

Working on a Node.js project with the express framework and utilizing EJS as the template engine, my IDE of choice is Visual Studio. Encountering an issue when using EJS variables within the same ejs file. Though it renders correctly and functions perfect ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

What steps are involved in setting up a search results page for example.com/s/keyword?

app.js app.get('/results',showResult) var express = require('express') var n = req.query.query; mysql_crawl.query('SELECT prod_name, full_price FROM `xxx` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, p ...

Learn how to use the Firebase Adapter for Next Auth to easily sign in using your email and password

I am currently using next-auth along with a Firebase adapter for authentication, but I am uncertain about the correct way to sign in users. I do not want to utilize my Google account for signing in; instead, I have user accounts within a Firebase project a ...

Incorporate real-time calculations using JavaScript (jQuery) with variables including initialization in HTML code

As a newcomer to JavaScript, I am encountering an issue that I need help with: I would like to convert the value in the number box into the answer next to it without any changes to the value. This should also include the variables NP0, NP1, and DP0 from t ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

Implementing a file size restriction in C# when writing a lengthy JSON string using the System.IO.Stream

I have a large array stored in Json format, and the result is saved in a variable called "sz" (string). However, when I attempt to save this Json result (string sz) to a file, it seems that not all of the string gets saved. Why is this happening? The siz ...

Creating a webpage that loads directly to a specific section of content

After searching online, I couldn't find the solution I was looking for. My goal is to have the visible part of the page load halfway down the actual page. This way, when users visit the site, they can immediately scroll up to see more content. I hope ...

Invoking a function passed via props that utilizes react-router's features

I'm really struggling to grasp this problem. Is there anyone here who could help me out? I have a component where I pass a method called this.fetchContent as props named Filter. This method triggers an action creator that uses axios with Redux to fetc ...

Navigating through an ajax-based webpage entirely with selenium webdriver

I have attempted to scroll a page entirely using the following code: var scrollToBottom = function() { window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight)); }; window.on ...

Adjust CardMedia Images to match their content in the new MUI 5 version

I’m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

Observable in RxJS with a dynamic interval

Trying to figure out how to dynamically change the interval of an observable that is supposed to perform an action every X seconds has been quite challenging. It seems that Observables cannot be redefined once they are set, so simply trying to redefine the ...

The promise catch method does not handle JSON parsing correctly

Utilizing Angular's Http to interact with my API has been successful for handling responses with a status of 200. The data is parsed correctly and outputted as expected within the first .then() block. However, when encountering an error with a status ...

Retrieve the heading of a click-able element using jQuery

My challenge involves a list of selectable buttons with names generated dynamically from a JSON file. Each time a button is clicked, I aim to retrieve its title, which corresponds to row["name"]. Below is my relevant code snippet and the JSON data provided ...

Injecting arbitrary text following ?= in a web URL

Consider the following code snippet for a page named MyWebsite.com/page.php <?php $username = "SuperUsername"; $password = "SuperPassword"; if (isset($_GET['p']) && $_GET['p'] == "login") { if ($_POST['user&ap ...