Composable Custom Data Types

In JavaScript, the easiest way to compose is function composition, and a function is just an object you can add methods to. In other words, you can do this:

 1 const t = value => {
 2   const fn = () => value;
 3 
 4   fn.toString = () => `t(${ value })`;
 5 
 6   return fn;
 7 };
 8 
 9 
10 const someValue = t(2);
11 
12 console.log(
13   someValue.toString() // "t(2)"
14 );

This is a factory that returns instances of a numerical data type, t. But notice that those instances aren’t simple objects. Instead, they’re functions, and like any other function, you can compose them. Let’s assume the primary use case for it is to sum its members. Maybe it would make sense to sum them when they compose.

The following code ...

Get Composing Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.