Today, we’re going to dive deep into the world of JavaScript’s prototype functions. Prototypes are a powerful feature of JavaScript, allowing us to add new methods to existing objects. Let’s explore how to create two custom prototype functions that can map one set of numbers to another set of values and constrain a number between a minimum and maximum value.
Mapping One Set of Numbers to Another
The first function we’re going to discuss is a mapping function. It helps us to map one set of numbers to another set of values. Here’s how you can extend the Number prototype to include a map function:
Number.prototype.map = function (in_min, in_max, out_min, out_max) {
return ((this - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min;
};
With this function, you can now transform any number from an initial range to another range. This can be extremely handy in data visualization or game physics, among other applications.
Constrain a Number Between Minimum and Maximum
The second function we’re going to discuss is a function that constrains a number between a minimum value and a maximum value. This is particularly useful when you need to ensure a number stays within a particular range.
Here’s how you can add a constrain function to the Number prototype:
Number.prototype.constrain = function (min, max) {
return Math.min(max, Math.max(min, this));
};
With this function, any number that is less than the minimum value will be set to the minimum value and any number that is more than the maximum value will be set to the maximum value.
Combining the Map and Constrain Functions
Now that we have our map and constrain functions, we can combine them to map a number from one range to another, and then ensure that it remains within the desired range.
Here’s an example of how you can use these functions together:
(123).map(0, 500, 0, 100).constrain(0, 100);
In this example, we’re mapping the number 123 from a range of 0 to 500 to a range of 0 to 100. This gives us 24.6. However, if the input number was out of the original range (either less than 0 or greater than 500), the map function wouldn’t account for that. But with our constrain function, we ensure that the final result stays within the 0 to 100 range.
And there you have it! We’ve just explored how to extend the JavaScript Number prototype with two extremely useful functions, providing us with the ability to easily map and constrain numbers. Happy coding!
Buy Me a Coffee