Adjust the range to match the specified step increment

I have an array of numbers like this:

const dataset = [0.5, 2, 1, 93, 67.5, 1, 7, 34];

The minimum value is 0.5 and the maximum value is 93. I want to round the extremes of this dataset to a specified step value.

For example:

  • If step = 5, the result should be [0, 95]
  • If step = 10, the result should be [0, 100]

The new minimum value should always be less than or equal to the actual minimum value in the dataset, and the new maximum value should always be greater than or equal to the real maximum value in the dataset. Both values should also be multiples of the specified step.

Note: It would be great if this also works with negative values.

I've created a function called roundToNearest, but it's not enough to solve my problem:

function computeExtremisRounded(dataset: number[], step: number): [number, number] {
   const [minValue, maxValue] = getMinAndMax(dataset) // assuming it exists
   const roundedMinValue = roundToNearest(minValue, step)
   const roundedMaxValue = roundToNearest(maxValue, step)
   return [roundedMinValue, roundedMaxValue]
}

function roundToNearest(value: number, step: number): number {
  return Math.round(value / step) * step;
}

Answer №1

When you need to determine the maximum or minimum value, make sure to round up or down accordingly:

function calculateRoundedExtremes(dataSet: number[], increment: number): [number, number] {
   const [minVal, maxVal] = findMinAndMax(dataSet) // assuming it's available
   const roundedMinVal = Math.floor(minVal / increment) * increment
   const roundedMaxVal = Math.ceil(maxVal / increment) * increment
   return [roundedMinVal, roundedMaxVal]
}

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

A loop variable in Javascript is a function that iterates

var x = 99; while (true) { function lyrics(person) { return x + " " + "lines of code in the file " + x + " " + person + (x-1) + " lines of code" + "!"; } console.log(lyrics("John strikes one out, clears it all out ;")); x -= 1; if (x ...

Encountering "Unexpected token *" error when using Jest on an import statement

What could be the reason for Jest failing with the error message "Unexpected token *" when encountering a simple import statement? Error log: Admin@Admin-PC MINGW32 /d/project (master) $ npm run test > <a href="/cdn-cgi/l/email-protection" class="__ ...

Error: API Not Responding to Switch Button Commands

I'm encountering an issue with a switch button that is based on an API. Initially, the button changes from "on" to "off" in my view when clicked. However, when I click the button to turn it back "on", it doesn't work. What's even more peculi ...

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

Is it possible to utilize Javascript object attributes as a designated HTML class?

I have a project where I am utilizing Javascript objects to store data in a table structure, similar to the example below: { name: toast, id: 15, style: small, }, { name: bagel, id: 17, style: medium, }, Is there a way to use the style attribute as ...

Tips for fixing CORS error when working with the fetch API

I'm having trouble retrieving data from the metaweather.com API using JavaScript's fetch function. I attempted to include before the API URL, but it has not resolved the issue. I followed a video tutorial on how to fetch data, but I'm stil ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

Getting AJAX to function on a local server with either XAMPP or node.js

I am completely stumped and in need of some assistance. My current challenge involves trying to implement AJAX on a local server, but I am feeling lost when it comes to even the most basic coding. I have installed node.js and XAMPP to my system and have b ...

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...

Delete the selected background color from custom drop-down lists in versions of Internet Explorer 9 and earlier

In my asp.net application, I have a dropdown element. I am trying to remove the default blue background color that appears when the dropdown is selected, as shown in the image below. I have tried all the solutions provided in this link, but none of them s ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

Tips on preventing the duplication of component instances in your project

Check out the plunker link to see that the child component "Loader" is being loaded multiple times every time the button is clicked. How can I prevent creating multiple instances of the same component? I want the new instance to replace the existing one wh ...

What is the reason behind TypeScript selecting a different overload when referencing a function versus when calling it within a lambda wrapper?

What is the reason for TypeScript selecting the last overloaded variant instead of the middle one in the last case, resulting in a type of (string | null)[] instead of string[]? (Version 4.4.4 of TypeScript) function f(x: null): null; function f(x: string ...

Newbie inquiry regarding the setup and utilization of Bootstrap

I'm currently working on building a website and I decided to incorporate a bootstrap carousel. Initially, I had a dropdown button in the navbar along with a collapsible menu for smaller viewports which were functioning properly. However, when I added ...

Using the googleapis library within HTML is not permitted

I have been attempting to execute a simple function (uploadFile(test.txt)) within an HTML file, but I am encountering issues as my app.js and Google APIs are not being recognized or called. Node.js is throwing this error: Uncaught ReferenceError: uploadFi ...

Resolving a CSS Layout Dilemma: How to Overlay Sidebar on Wrappers

I've run into a challenge while attempting to position a sidebar over page wrappers. The issue with absolute positioning arises when the sidebar needs to align with the corner of the blue header. I have contemplated using JavaScript to maintain its cu ...

What is preventing TypeScript from recognizing enums in libraries?

Check out the TypeScript types defined for html-validator: declare namespace HtmlValidator { // ... enum ValidationResultsOutputFormats { json = 'json', html = 'html', xhtml = 'xhtml', ...

Mistakes in serializing arrays for javascript in an ajax request

I am trying to send an array of JavaScript objects in an Ajax call. This is how I create my array: var itemsToEdit = []; $(".editedItem[value='true']").closest("tr").each(function() { var itemToEdit = { id: $(this).find(".i ...

Different ways to save data fetched from a fetch request

I'm fairly new to React and could use some assistance. I am trying to retrieve data from a movie database based on a search term. I have a method called getMovies where I utilize fetch to grab the data. The information is located in data.Search, but I ...

Is it a good idea to relocate the document.ready function into its own JavaScript function?

Can the following code be placed inside a separate JavaScript function within a jQuery document.ready, allowing it to be called like any other JavaScript function? <script type="text/javascript"> $(document).ready(function() { $('div#infoi ...