In the earlier lessons, you ported the Learn to Boulder class’s warning and its reminder. The next job comes from the gym’s manager. Wednesday is student night, and every bill gets twenty percent off.
The Python script on the desk laptop doesn’t hard-code that rate into a discount function. It has a function that builds discount functions, and others that build on it. In this lesson, you’ll port them to JavaScript, where they take less ceremony than in Python.
Make a Discount Function
In Python, make_discount() takes a rate and returns a lambda that applies it. The desk calls it once for student night and keeps the result:
def make_discount(rate):
return lambda amount: amount * (1 - rate)
student_night = make_discount(0.2)
print(f"£{student_night(18):.2f}")
That prints £14.40 for an adult with shoes. In JavaScript, the same factory fits on one line, as an arrow that returns an arrow:
const makeDiscount = (rate) => (amount) => amount * (1 - rate);
const studentNight = makeDiscount(0.2);
console.log(studentNight(18));
console.log(`£${studentNight(18).toFixed(2)}`);