Created
June 4, 2021 14:46
-
-
Save gitdagray/40d7117dcea6ea1274cd68f8204a3896 to your computer and use it in GitHub Desktop.
Functional composition for Vehicle and Motorcycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent. Thank you