Passing a rule to another operation
A report can include values according to different policies. Rather than copy the reporting operation, we can supply the decision as a function. A function passed to another function is a callback. The word does not imply asynchronous execution.
const isPositive = function (value) {
return value > 0;
};
const isLarge = (value) => value > 100;
function checkValue(value, rule) {
return rule(value);
}
console.assert(checkValue(5, isPositive));
console.assert(checkValue(120, isLarge));
A function expression creates a function value assigned to a name. An arrow function is another syntax. An expression after the arrow is returned implicitly. A block after the arrow needs an explicit return to provide a value.
Pass isPositive, not isPositive(): the first is the function, the second calls it immediately without the intended input. Ordinary and arrow functions differ in behaviors such as this; they are not universally interchangeable. Here we use simple input/output callbacks without those features.
Guided correction
The callback (value) => { value > 0; } returns undefined because the comparison result is discarded. Either add return inside the braces or use the expression form shown above. Shortness does not guarantee clarity.
Independent lab: decompose a quote
Create separate functions for subtotal, discount and formatting. Have one coordinating function call the calculations, then return the final number. Print only at the outermost call. Test an order of three items at 20 with a 10% discount and no other charges.
One possible correction
function calculateSubtotal(price, quantity) {
return price * quantity;
}
function applyDiscount(amount, rate) {
return amount * (1 - rate);
}
function quote(price, quantity, rate) {
return applyDiscount(calculateSubtotal(price, quantity), rate);
}
const formatTotal = (amount) => `Total: ${amount}`;
console.assert(quote(20, 3, 0.10) === 54);
console.log(formatTotal(quote(20, 3, 0.10)));
Each part has a purpose; avoid extracting meaningless one-line wrappers merely to increase the function count. The next modules use callbacks to express collection operations clearly.