Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does)

Here is the function I came up with (using TS)

function clamp(value: number, min: number, max: number) {
  return Math.min(Math.max(value, min), max)
}

However, there are certain scenarios where I don't want to manually convert all three params to type Number before passing them into the function. One approach I thought of was like this:

function clamp(value: number, min: number, max: number) {
  return Math.min(Math.max(Number(value), Number(min)), Number(max))
}

This involves converting each individual param to type Number.

Is there an alternative method to convert all params to type Number in one go?

I am still on the lookout for simpler solutions! 🫠

Answer â„–1

To convert all values to the Number data type in one go, you can utilize the Array.map method. Below is how it can be achieved using plain old JavaScript:

function convertToNumbers(...values) {
  return values.map(Number).filter(v => !isNaN(v));
}

console.log(`${convertToNumbers(1,`26`, 42)}`);
console.log(`${convertToNumbers(...[...`123`])}`);
console.log(`${convertToNumbers(`20`, `+`, `22`, `=`, 42)}`);
console.log(`${convertToNumbers(...(`20+22=42`.split(/[+=]/)))}`);

In Typescript (check this out as well...)

function restrictToRange(...values: Array<number|string>) {
  const numbers: (number|Nan)[] = values.map(Number);
  if (numbers.filter(v => !isNaN(v)).length === 3) {
    const [value, min, max] = numbers;
    return Math.min(Math.max(value, min), max);
  }
  return `insufficient argument(s)`;
}

console.log(restrictToRange(42));
console.log(restrictToRange(1,3,`42`));

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

What are some ways to enhance this TypeScript code using Functional Programming with the FP-TS library?

i am struggling to write some typescript code using fp-ts Below are the tasks that i want the algorithm to carry out: Once a path is received from the command line, it should check if the given path exists search for all files in the directory and locat ...

Encountering problems with ajax technology

As a newcomer to Laravel and Ajax, I am facing an issue with displaying the state of the selected country in a dropdown list. Although the data is successfully fetched from Laravel and received through Ajax, I am struggling to dynamically add it to the H ...

Creating stunning light effects with camera flash using three.js

I'm working on a website using the amazing three.js library. My current challenge is figuring out how to incorporate a camera flash effect into three.js. Currently, I have a rotating cube in my scene and I would like to have a camera flash occur after ...

The filtering feature in AngularJS ng-options is not functioning correctly

Greetings, I am a newcomer to angular. In my current demo application, I have created a list of users with a select filter using ng-option. There seems to be a bug that I have been unable to identify. The issue: When I select the Female option, i ...

What is the best way to deliver data from the main Vue instance to components that are being utilized by vue-router?

Currently, I am utilizing vue-router within a single HTML file instead of using separate file components. I am encountering an issue where I am unsure how to pass the data stored in the Vue data object to the component when loading it for a route. Oddly e ...

Encountering an issue with accessing a property in Angular's TypeScript module

I encountered an issue while trying to access a property of a static array that I created in a TypeScript class. The error message I received is as follows: ERROR TypeError: Cannot read property 'forbiddenProjectNames' of undefined Below is th ...

Issue with Switch Map in Angular 2 and RxJS

I'm currently implementing an infinite scrolling feature in my application using a specific component for managing scroll events. When the scroll reaches the bottom of the div, I trigger a function to fetch more data. Everything seems to be working fi ...

The issue with the callback function not being triggered within a self-repeating loop

As I work on creating a user-script to incorporate a trailer video into a website, I encountered an issue with the callback function in my script. The goal is to filter the real source of the video from different URL formats, but for some reason, the callb ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

Deliver a numerical input to the component on an equivalent hierarchical tier

I need to find a way to pass the values of the "things" array to another component on the same level in my app. The structure of my app is as follows: sidebar.component data.service body.component In the sidebar component, I have a button that triggers a ...

Ways to make the submenu display underneath the main menu

Click here to view the menu It is important to note that you may need to expand the Result Box in order to see the full menu. The issue I am currently facing involves fixing a submenu that appears when hovering over the Men and Women <li> elements. ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

When the window is fully loaded, JavaScript executes

Can someone help me set up this script to start running when the page loads? I want the vat field to automatically show up if the company name has been entered. Thank you! //--></script> <script type="text/javascript>//-- $('.colorbox ...

The filter on the mobile version is not displaying correctly

When I select a category in the input filter, only items with the same category are displayed when clicked. However, when I click on "Others" on the desktop version, only rows with that category are shown, but on mobile after resizing and filtering, nothin ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Using the function goToPage() within the TabbedHeaderPager component

I am currently working on a project that involves using TabbedHeaderPager, and I need to change tabs programmatically. I have been attempting to use the function goToPage() but have run into difficulties accessing it. I have tried passing it as a prop an ...

When attempting to log API results in Next.js, a TypeError occurs because the property is undefined

I'm encountering a rather unusual error. In my Next.js app, I am attempting to console log the results of an API call to see what data I receive. The API function is responsible for verifying if a user is logged in, and if they are, I render a specifi ...

Unusual TypeScript Syntax

While examining a TypeScript function designed to calculate average run time, I stumbled upon some unfamiliar syntax: func averageRuntimeInSeconds(runs []Run) float64 { var totalTime int var failedRuns int for _, run := range runs { ...