Skip to content

Instantly share code, notes, and snippets.

@jsmanifest
Created November 24, 2019 21:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jsmanifest/5f92cbcbd2b00fc5c2cd32de44dcef59 to your computer and use it in GitHub Desktop.
Save jsmanifest/5f92cbcbd2b00fc5c2cd32de44dcef59 to your computer and use it in GitHub Desktop.
class FrogBuilder {
constructor(name, gender) {
// Ensure that the first character is always capitalized
this.name = name.charAt(0).toUpperCase() + name.slice(1)
this.gender = gender
}
formatEyesCorrectly(eyes) {
return Array.isArray(eyes) ? { left: eye[0], right: eye[1] } : eyes
}
setEyes(eyes) {
this.eyes = this.formatEyes(eyes)
return this
}
setLegs(legs) {
if (!Array.isArray(legs)) {
throw new Error('"legs" is not an array')
}
this.legs = legs
return this
}
setScent(scent) {
this.scent = scent
return this
}
updateTongueWidthFieldName(tongue) {
const newTongue = { ...tongue }
delete newTongue['tongueWidth']
newTongue.width = tongue.width
return newTongue
}
setTongue(tongue) {
const isOld = 'tongueWidth' in tongue
this.tongue = isOld
? this.updateTongueWidthFieldName(tongue, tongue.tongueWidth)
: tongue
return this
}
setHeart(heart) {
this.heart = heart
return this
}
setWeight(weight) {
if (typeof weight !== 'undefined') {
this.weight = weight
}
return this
}
setHeight(height) {
if (typeof height !== 'undefined') {
this.height = height
}
return this
}
build() {
return new Frog(
this.name,
this.gender,
this.eyes,
this.legs,
this.scent,
this.tongue,
this.heart,
this.weight,
this.height,
)
}
}
const larry = new FrogBuilder('larry', 'male')
.setEyes([{ volume: 1.1 }, { volume: 1.12 }])
.setScent('sweaty socks')
.setHeart({ rate: 22 })
.setWeight(6)
.setHeight(3.5)
.setLegs([
{ size: 'small' },
{ size: 'small' },
{ size: 'small' },
{ size: 'small' },
])
.setTongue({ tongueWidth: 18, color: 'dark red', type: 'round' })
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment