6/20/2023 0 Comments Convert number javascript![]() ![]() ![]() ![]() This would improve the performance if you were converting many values from the same range. The only optimization possible is to remove the division (multiplication is quicker than division). To further remove code noise use an arrow function and shorten the argument names const rescale = (val, oMin, oMax, min, max)=>(val - oMin) * (max - min) / (oMax - oMin) + min return (number - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin return (((number - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin However I would never guess what this function did without some extra information The function name is too long convertValueToBoundary the conversion is implied and value is commonly shortened to val so valToBoundary is less noisy. Your naming and code style make the code very noisy. The conversion should be conducted without the use of any native language functions as I plan to use the same formula across different languages and platforms. Given a scenario where this needs to execute multiple times in rapid succession, it would be ideal to have this execute with the least amount of arithmetic operations required. Is this the optimal way to conduct this calculation? After a number of different attempts the above formula is the best I could come up with. Return (((number - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMinįormula newValue = (((oldValue - oldMinimum) * (newMaximum - newMinimum)) / (oldMaximum - oldMinimum)) + newMinimumįor instance, given the number 5 within a range of 0-10, we want to increase the numerical range to be between 0-100 instead. * int The original number converted to the new boundary.įunction convertValueToBoundary(number, oldMin, oldMax, newMin, newMax) * int newMax The new maximium value to convert to. * int newMin The new minimum value to convert to. I have a function that takes a specific number and a range, and re-scales it to the corresponding number in a different range. ![]()
0 Comments
Leave a Reply. |