Number helpers
- Node.js course
- Intermediate
- Lesson 21/116
- 6 min
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.
Practice 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)).
Starter code
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"));
// Add the clamp method
// write here
// Call clamp and print the result
// write hereSample 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));Expected output
Hazır Merhaba 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
clamp |
Keeps value in range |
min |
Lower bound |
max |
Upper bound |
value |
Value being checked |
2 Complete the clamp body
if (value < min) return min; if (value > ____) return max; return value;
if (value < min) return min; if (value > max) return max; return value;
Explanation: If the value is above the maximum, max is returned.
3 What does helpers.clamp(15, 0, 10) return?
helpers.clamp(15, 0, 10)- 10 Correct answer
- 15
- 0
- 5
Explanation: 15 is greater than 10, so 10 is returned.