Skip to content

Instantly share code, notes, and snippets.

@pufface
Last active May 5, 2019 10:57
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 pufface/8f13cdf426e3ea6d685847fd6f9bc9c4 to your computer and use it in GitHub Desktop.
Save pufface/8f13cdf426e3ea6d685847fd6f9bc9c4 to your computer and use it in GitHub Desktop.
class Shape {
constructor() {
this.type = this.constructor.name
}
}
class Square extends Shape {
constructor(side) {
super()
this.side = side
}
}
class Circle extends Shape {
constructor(radius) {
super()
this.radius = radius
}
}
class Rectangle extends Shape {
constructor(width, height) {
super()
this.width = width
this.height = height
}
}
const shapes = [new Circle(4.0), new Square(5.0), new Rectangle(6.0, 7.0)]
const matcher = function(pattern) {
return shape => pattern[shape.type](shape)
}
const area = matcher({
Square: square => square.side * square.side,
Circle: circle => circle.radius * circle.radius * Math.PI,
Rectangle: rect => rect.height * rect.width
})
const totalArea = shapes.reduce((acc, shape) => acc + area(shape), 0)
console.log(`Total area: ${totalArea}`)
const perimeter = matcher({
Square: square => 4 * square.side,
Circle: circle => 2 * Math.PI * circle.radius,
Rectangle: rect => 2 * rect.height + 2 * rect.width
})
const totalPerimeter = shapes.reduce((acc, shape) => acc + perimeter(shape), 0)
console.log(`Total perimeter: ${totalPerimeter}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment