Skip to content

Instantly share code, notes, and snippets.

@softwarebygabe
Last active June 22, 2020 20:02
Show Gist options
  • Save softwarebygabe/2f5a9ffed266735c4a74701fdf5dfd15 to your computer and use it in GitHub Desktop.
Save softwarebygabe/2f5a9ffed266735c4a74701fdf5dfd15 to your computer and use it in GitHub Desktop.
type Material = 'wood' | 'brick' | 'steel'
type HouseOption = (h: House) => void
class House {
private rooms: number
private floors: number
private material: Material
constructor(...options: HouseOption[]) {
// defaults are clear
this.rooms = 1
this.floors = 1
this.material = 'wood'
// set the options
for (const option of options) {
option(this)
}
}
public static WithRooms(roomCount: number): HouseOption {
if (roomCount < 1) {
throw new Error('a House can not have less than 1 room!')
}
return (h: House): void => {
h.rooms = roomCount
}
}
public static WithFloors(floorCount: number): HouseOption {
if (floorCount < 1) {
throw new Error('a House can not have less than 1 floor!')
}
return (h: House): void => {
h.floors = floorCount
}
}
public static WithMaterial(material: Material): HouseOption {
return (h: House): void => {
h.material = material
}
}
}
@softwarebygabe
Copy link
Author

construction:

const myHouse = new House(
  House.WithRooms(5),
  House.WithFloors(2),
  House.WithMaterial('wood')
)

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