Functional Composition and Mix-Ins in JS

Daoud Merchant
6 min readMay 15, 2022

--

(or Let Me Teach You a Game)

Hi! I’m Daoud, a JavaScript developer with a long history in education. I’ll try to explain some beginner-intermediate JS concepts with analogy, code examples and *zero* foo and bar (I promise!) Feel free to contact me if you have any questions about what I’ve written.

Prerequisites:

This follows my previous post on inheritance, and continues its story. As I will be using mix-ins rather than basic composition to create a functional equivalent of a two-level classical hierarchy, this may be considered a more intermediate-level article and you may wish to come back to it later depending on your skill level. Note that my code represents just one functional approach to object creation (functional programming’s purpose is its flexibility after all), and you may wish to begin with more straightforward ‘factories’ before experimenting.

Photo by Lucas George Wendt on Unsplash

The Hierarchy

Things are going well at The Company. Helen (the head of Finance who head-hunted you) confidently manages her team as they look after the budget. You’re even still friends with Jon who (through sheer length of tenure) now somehow manages his own team, though when he discusses what he teaches them he always seems pretty vague. People in their teams learn different skills, but everyone still borrows the Boss’ stapler.

It is as it has always been there.

One day, you notice two workers laughing by the water-cooler (you recognise them from Finance). Jon, who always seems to have infinite time on his hands, rushes over to ask what was so funny. “Oh”, begins the first worker, “we have this game… No. Forget it, it’s stupid.”

You know Jon well enough to know that this is exactly how to pique his interest; his eyes sparkle. “Tell me about it, I’m interested…”

The second worker looks at his colleague. “Well… Helen teaches it to new recruits now. When they sign on at Finance they get to pick a nickname. For each round, two players pick a number between 1 and 10 and the person with the higher number gets to rule the world!”

‘Wow, that is stupid’, you think; clearly, Jon is of a different opinion. Practically buzzing with excitement, he asks hungrily if they can teach it to him.

The two workers look at each other puzzled… “I don’t know how that would work”, begins the first. “We need Finance to tell us what to do when we play. And how would you choose a nickname? We chose one because we were specifically asked to pick one by Finance. And anyway, you only answer to the Boss, it would feel weird teaching a superior something.”

They seem worryingly unintelligent, but Jon is unfased. “Can’t the Boss learn the rules so he can teach me?”

“The Boss?” The second worker is visibly startled. “You really think he’s going to start asking HR to quiz people for nicknames when they join the company? And even if he did agree, this is a cool game for cool people. We’d be happy for your team to join in, but if the Boss can teach anyone the game who’s to say everyone won’t be out here spending their lunch break picking numbers?!”

Welcome to the big problem with Object Oriented Programming: classes can diverge infinitely but they can never converge. There’s no way to teach both Jon’s team and Finance pickNumber() and to ask them both nicknames without it being ‘lifted’ above them on a shared prototype. And what if Finance and Jon’s department had sub-divisions (extended classes)? They’d all learn the game automatically.

Jon, looking utterly defeated, wanders back to his desk.

A big meeting is called the following week: the Boss has been embezzling money and his contract terminates immediately. One of the higher-ups has promoted his son, who emerges in front of the crowd in a blazer, shorts and sandals.

“I think we’ve all had quite enough of the old Boss’ toxic dogma. Rule #1: you can use as much money as you want (you can use more computer memory). Rule #2: from now on, you are your own bosses!” He stands smiling, anticipating applause. People look at each other nervously.

“…Our own bosses? So who teaches people when they join?”

“Pick someone!”

“And who will run the departments?”

“Departments are an illusion of the social construct. You choose what you want to do!”

People are dumbfounded. This Platonian republic of an office isn’t what people expected when they came in to work today. The new ‘boss’, evidently pleased with the disruption he’s caused, puts on his sunglasses and heads out to his Ferrari. Before passing through the door, he turns around for one last comment: “And no more damn loose documents!”

The door closes behind him. You realise you’re all going to have to rethink what it means to be an employee.

Welcome to ‘factory functions’! If a class populates an object created with a constructor call (new), ‘factory functions’ are simply functions which return a new object. Every time they’re called, they spit out a shiny new object ready to use how you want!

So what have I done in the code above? I’ve made a factory which takes a ‘documents’ object as a parameter, uses it as ‘state’ (it has exclusive closure over it), reveals it on a getter and only allows mutation via two exposed methods: set() and add(). Make sure you’re comfortable understanding the above factory before you keep reading. If you’re used to OOP, what’s coming will feel very new.

After a while, Jon starts laughing. Everyone turns to look at him; “well, it looks like my life just got a whole lot easier around here. Anyone want to learn how to make their lives easier too, come see me.”

Can you see what’s going on above? It’s a function which takes an ‘employee’ (returned by our factory), glues on a new method taking advantage of set() and returns it. All it does is add functionality to whatever it receives: it is a ‘mix-in’.

“And I can teach you finance!” Helen’s waving her hand in the crowd with her trademark energy.

Another person steps forwards. “Hey, does anyone here even know how emails work? The old Boss had us working with loose documents so long I don’t even know where my mouse is. Anyway, for those that need it, I can teach you that too.”

“Wait wait wait, this is getting confusing…” Yet another helpful worker’s speaking up. “Anyone else here confused? You’re going to be learning multiple skills from multiple people now, how are you going to keep organised? If you want, my role can be helping you get sorted out with all of them.”

Note that we now have a mix-in handler, but each mix-in works completely independently; you can include as many or as few as you want, and in any order. Anyone can learn any specific combination of skills whenever they want!

Suddenly, like a flash, Jon has a revelation. He dashes to someone in the crowd — it’s that finance worker who was by the cooler. “YOU!” (It seems he doesn’t realise he’s shouting.) “You can teach me the game now?”

“…but you have to pick a nickname…”

“BEAST BOY.”

Hours later, you come in your front door and hang up your coat. Your roommate can see something’s changed: “What happened?”

“Oh, weird day, there was this guy in shorts and everyone was teaching everyone else stuff and there’s this stupid game with numbers…”

“I love games! Can you teach me?”

‘She’s not even an employee’, you think, ‘she can’t play if all she knows are the rules… can she?’

“No way Shreddinator rules the world. Rematch.”

You order pizza.

--

--