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 is the best way to determine the data type of an object retrieved from an API in TypeScript

Hey there, I'm currently developing a web application using Angular 2 and I'm focusing on implementing an exception handling mechanism. To achieve this, I've created a model that mirrors the object structure I will receive from the server (E ...

Optimizing Wordpress by Efficiently Enqueueing Javascript

As a beginner with a WordPress website, I am aware that in order to execute scripts on a WordPress page, they need to be enqueued in the functions.php file. However, I'm unsure about the correct process for this. The specific JavaScript file I want t ...

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

How do I implement a dynamic input field in Angular 9 to retrieve data from a list or array?

I'm looking to extract all the strings from the Assignes array, which is a property of the Atm object, and populate dynamic input fields with each string. Users should be able to update or delete these strings individually. What approach can I take us ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

Obtain base64 representation of a file using plupload file uploader

I am currently utilizing the Plupload Uploader. My objective is to convert the uploaded file to base64 and transmit it within a SOAP envelope. I have successfully created the envelope and utilized my web-service. However, I am wondering how I can retrieve ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

Within Angular, the Subscribe function is invoked after all other methods in the component have been executed. Consequently, this sequence of events often prevents me from effectively utilizing the response data

Struggling with implementing await and async in TypeScript, especially as a beginner. Below is how I attempted to use them: async refreshList(){ await this.service.refreshList().subscribe(res => { console.log(res); this.service.todoListModel=res; ...

Ensure that the MUI icon color is set accurately

I created a functional component to set default values for react-admin's BooleanField. Here is the code: import ClearIcon from '@mui/icons-material/Clear' import DoneIcon from '@mui/icons-material/Done' import get from ...

Encountering an error while compiling the Angular 8 app: "expected ':' but got error TS1005"

As I work on developing an Angular 8 application through a tutorial, I find myself facing a challenge in my header component. Specifically, I am looking to display the email address of the currently logged-in user within this component. The code snippet fr ...

Is conditional CSS possible with NextJS?

While working on an animated dropdown for a navbar, I came across this interesting dilemma. In a strict React setup, you can use an inline if/else statement with onClick toggle to manage CSS animation styles. To ensure default styling (no animation) when ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

Tips for sending an Ajax request to a separate URL on the same server

When making an ajax request to my server, I use the following code: var data = ''; $.ajax({ type: 'GET', url: 'api/getnews/home/post/'+title, data: data, datatype: 'json', success: f ...

Tips for serving images locally instead of using an online URL when exporting with Next.js static:

I've encountered an issue where multiple images pulled from an online source are not being included in my export when I start the process. The image URLs are stored as strings online, but I want them to be saved locally and exported that way instead o ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

Identify when the user ceases typing in Angular 2

I am currently working on implementing a feature that detects whether the user is typing or not. I need to determine when the user has stopped typing for at least 3 seconds in order to perform certain actions. I have successfully detected when the user sta ...