Skip to content

Instantly share code, notes, and snippets.

@gitdagray
Created June 4, 2021 14:46
Show Gist options
  • Save gitdagray/40d7117dcea6ea1274cd68f8204a3896 to your computer and use it in GitHub Desktop.
Save gitdagray/40d7117dcea6ea1274cd68f8204a3896 to your computer and use it in GitHub Desktop.
Functional composition for Vehicle and Motorcycle
// Define methods first. They can be used when building any object.
const readyToGo = () => {
return {
readyToGo() { console.log('Ready to go!') }
}
}
const wheelie = () => {
return {
wheelie() { console.log('On one wheel now!') }
}
}
// Returns a vehicle object that uses the readyToGo method
const createVehicle = () => {
return {
wheels: 4,
motorized: true,
...readyToGo()
}
}
// Needs a vehicle object (compare to ES6 extends with super())
// Overwrites the wheels property
// Returns a motorcycle object that has both readyToGo and wheelie methods
const createMotorcycle = (vehicleObj) => {
const motorcycle = { ...vehicleObj };
motorcycle.wheels = 2;
return {
...motorcycle,
...wheelie()
}
}
// Create a car for Dave
const davesCar = createVehicle();
console.log(davesCar);
console.log(davesCar.wheels);
davesCar.readyToGo();
// Create a motorcycle for Dave
const davesBike = createMotorcycle(davesCar);
console.log(davesBike);
console.log(davesBike.wheels);
davesBike.readyToGo();
davesBike.wheelie();
@praveenchandran81
Copy link

Excellent. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment