Whenever I attempt to trim my integer within a for loop, my browser consistently becomes unresponsive and freezes

I am facing an issue with my code that generates alcohol percentage, resulting in values like 43.000004 which I need to trim down to 43.0, 45.3, etc. However, whenever I try to use any trim/parse functions in JavaScript, my browser ends up freezing.

Below is the code snippet:

incrementAlcohol() {
  // Initialize an empty array.
  let alcoholData = []

  // Iterate through the array from 40 to 95 with increments of 0.1.
  for (let i = 40; i <= 95; i + 0.1) {
    // Trim the decimal places to 3 digits.
    parseFloat(i).toFixed(3)

    // Convert it into a string for the autocomplete component.
    i.toString()

    // Add it to the array.
    alcoholData.push({
      'id': i,
      'name': i + "%"
    })
  }

  // Return the processed alcohol data.
  return alcoholData
},

Answer №1

A potential solution is to develop a generator function that produces the current value and then enclose it in an array.

Furthermore, it's worth noting that the range ought to be inclusive/exclusive (max = end - step).

const generateRangeValues = function*(start, end, step, customFunction) {
  for (let val = start; val < end; val += step) {
    yield customFunction ? customFunction(val) : val;
  }
}

let alcoholData = [...generateRangeValues(40, 95, 0.1, (val) => {
  return ((fixed) => ({ id : fixed, name : fixed + "%" }))(val.toFixed(3));
})]

console.log(alcoholData);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Having trouble getting the items to show up on the canvas

I have been struggling to implement JavaScript on a canvas in order to display mice in the holes using the mouse coordinates. Despite trying many different methods and spending close to a month on this project, I still can't seem to get it to work acr ...

Configuration file stored within the node_modules directory

I have developed a generic npm package that contains my business logic. However, I require access to some information stored in my google cloud storage configuration files. How can I retrieve this data when my package is located within the node_modules fol ...

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

Using Leaflet to set the view based on a GeoJSON dataset

I am working on incorporating a leaflet.js map with a square shape imported from an external GeoJSON file. I have determined the exact coordinates for the center of the square, and now I need to convert these coordinates in order to pass them correctly t ...

How to implement form modal binding using Laravel and Vue.js

There are two models named Tour.php public function Itinerary() { return $this->hasMany('App\Itinerary', 'tour_id'); } and Itinerary.php public function tour() { return $this->belongsTo('App\Tour', ...

Retrieve the Checkbox id of a material-ui checkbox by accessing the object

I'm currently working on extracting the id of a Checkbox object in my JSX code. Here's how I've set it up: <div style={{display: 'inline-block', }}><Checkbox id='q1' onclick={toggleField(this)}/></div> ...

Creating a synchronous loop in Node.js with Javascript

After exhausting various methods such as async/await, synchronous request libraries, promises, callbacks, and different looping techniques without success, I find myself seeking help. The task at hand involves calling the Zoom API to fetch a list of cloud ...

Ignoring the incremented value in a jQuery function

I have been struggling to resolve this issue for quite some time now, and unfortunately, my lack of proficiency in javascript is hindering me. Here's a jfiddle with an interesting jquery code snippet that I came across: [html] <button id="addPro ...

Exploring the contrasting outcomes between a request post and an axios post

After using request and wrapping it with a promise, I realized that I could write cleaner code by switching to axios. However, I encountered an internal server error (Request failed with status code 401) and since I don't have access to the backend co ...

Is there a Node Package available for storing data indefinitely?

When I execute my code, I need to store a variable permanently. Is there a node package or another method to achieve this? I want to ensure that I can access the stored data even after restarting my server. For instance, in my file named "runMe.js": var ...

initiate a click event within another click event

This is an HTML Code snippet: <ul id="linkjess"> <li><a href="javascript:setfolder('medewerkers', '1000');">medewerkers 1000</a></li> <li><a href="javascript:setfolder('medewerkers', ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Using AJAX POST requests with PHP and SQL queries seems to function properly but unfortunately, it only

I am facing an issue with deleting an item from a list using AJAX, PHP, and MySQL. The first time I try to delete an item, the AJAX request works perfectly. However, on subsequent attempts, although the AJAX request returns success, the item is not deleted ...

Use the `string.replace()` method to swap out strings in a nested object with values from a separate file

Is there a way to swap out the placeholders __fruit_type__, __clothing_type__, __fitness_equipment__, __meditation_app__ in collection.js with the corresponding values from values.js? I'm attempting to do this using the string.replace() Method co ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

The AngularJS price slider may exceed its range if the ng-model is null or below the minimum value

I currently have an rz-slider featured on my webpage that is utilized for gathering the price of a product from the user. In addition to the slider, there are two input fields present which are designated for storing the minimum and maximum values. The ng- ...

vue popup input will automatically receive focus

Currently, I am utilizing Vue 2.x Within a HTML file that is included in a JSP file, the structure looks like this: <html> <body> <div id="myDiv"> <input type="text" v-model="input" @click=&qu ...

Opt for CSS (or JavaScript) over SMIL for better styling and animation control

I recently noticed an alert in my Chrome console that SVG's SMIL animations are being deprecated and will soon be removed. The message suggested using CSS or Web animations instead. Since I want to transition from SMIL to CSS animations, there are a ...

Refreshing a page will disable dark mode

I'm in the process of implementing a dark mode for my website using the code below. However, I've encountered an issue where the dark mode resets when refreshing the page or navigating to a new page. I've heard about a feature called localst ...