Building Functions From Functions

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:

Language: Python
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:

Language: JavaScript
const makeDiscount = (rate) => (amount) => amount * (1 - rate);

const studentNight = makeDiscount(0.2);
console.log(studentNight(18));
console.log(`£${studentNight(18).toFixed(2)}`);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.