Node.js
Number helpers
Add number conversion and calculation functions.
Number helpers
Now we add a number helper to the helpers object: clamp. This method keeps a value within a range. If the value is below the minimum it returns the minimum; if above the maximum it returns the maximum; otherwise it returns the value itself.
Example: helpers.clamp = function(value, min, max) { if (value < min) return min; if (value > max) return max; return value; }. The call helpers.clamp(15, 0, 10) returns 10, because 15 is greater than 10. clamp(-3, 0, 10) returns 0. This method is useful for clamping game scores, screen coordinates or percentage values. We take the previous lessons' solution and add this method.
Using clamp
Calling the clamp method is just like capitalize: helpers.clamp(15, 0, 10). After the previous lessons' output, the result is printed on a new line. This way the output keeps accumulating.
Output order: Ready, Hello, 10. Each lesson keeps the previous output and adds a new one. This shows the helper library growing step by step. The number 10 returned by clamp is printed directly with console.log; no extra conversion is needed.
Exercise Add the clamp method and call it
Take the previous lessons' solution. Add the helpers.clamp method with body if (value < min) return min; if (value > max) return max; return value;. Print the result with console.log(helpers.clamp(15, 0, 10)).
Show example solution
const helpers = {};
module.exports = helpers;
console.log("Ready");
helpers.capitalize = function(text) {
if (!text) return text;
return text[0].toUpperCase() + text.slice(1);
};
console.log(helpers.capitalize("hello"));
helpers.clamp = function(value, min, max) {
if (value < min) return min;
if (value > max) return max;
return value;
};
console.log(helpers.clamp(15, 0, 10));
Test yourself
-
Match each piece to its role
- clamp
- Keeps value in range
- min
- Lower bound
- max
- Upper bound
- value
- Value being checked
-
Complete the clamp body
if (value < min) return min; if (value > ____) return max; return value;
Show answer
if (value < min) return min; if (value > max) return max; return value;
-
What does helpers.clamp(15, 0, 10) return?
helpers.clamp(15, 0, 10)
Show answer
10 — 15 is greater than 10, so 10 is returned.
Next lesson: Date helpers