Skip to content

Instantly share code, notes, and snippets.

@kudapara
Created April 18, 2018 19:44
Show Gist options
  • Save kudapara/118efa912e962bf119ce74b0ffa78589 to your computer and use it in GitHub Desktop.
Save kudapara/118efa912e962bf119ce74b0ffa78589 to your computer and use it in GitHub Desktop.
Code that adheres to OCP
class Circle {
constructor (radius) {
this.radius = radius
}
area () {
return 2 * Math.PI * Math.pow(shape.radius, 2)
}
}
class Square {
constructor (length) {
this.length = length
}
area () {
return Math.pow(shape.length, 2)
}
}
class AreaCalculator {
constructor (shapes) {
this.shapes = shapes
}
sum () {
return this.shapes
.map((shape) => {
if (typeof shape.area === 'function') {
return shape.area()
} else {
throw new Error('The area you supplied does not conform to the area interface')
}
})
.reduce((totalArea, currentArea) => {
return totalArea + currentArea
}, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment