Member-only story
Functional programming (FP) differs significantly from object-oriented programming (OOP). Traditional concepts like inheritance don’t fit neatly within the confines of pure functional paradigms. Nevertheless, there exist creative techniques mimicking OOP inheritance using FP tools like higher-order functions and closures.
Consider the following case study, where we simulate inheritance by composing functions instead of deriving classes. Assume we’d like to represent geometric figures, each having a corresponding area formula and label.
const circle = radius => ({
label: 'Circle',
area() {
return Math.PI * radius * radius;
}
});
const rectangle = (width, height) => ({
label: 'Rectangle',
area() {
return width * height;
}
});
const triangle = (base, height) => ({
label: 'Triangle',
area() {
return 0.5 * base * height;
}
});
const shapes = [circle, rectangle, triangle];
shapes.forEach(factoryFn => {
const shapeInstance = factoryFn(Math.random() * 10);
console.log(`Created ${shapeInstance.label} with random side lengths:`);
console.log(`Area: ${shapeInstance.area()} \n`);
});