Skip to content

Instantly share code, notes, and snippets.

@miteshmap
Forked from jsmanifest/FrogBuilder.js
Created April 12, 2020 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshmap/8bc4d0ca7465c735dbba3f94c30131ff to your computer and use it in GitHub Desktop.
Save miteshmap/8bc4d0ca7465c735dbba3f94c30131ff 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()
@miteshmap
Copy link
Author

solution to code clutter for complex objects like - https://gist.github.com/jsmanifest/8e150cfd40fcbf23f822e7a2e5efaf8c#file-frog-js

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