|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +class Rect { |
| 4 | + constructor(x, y, width, height) { |
| 5 | + this.x = x; |
| 6 | + this.y = y; |
| 7 | + this.width = width; |
| 8 | + this.height = height; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +const equilateral = Category => class extends Category { |
| 13 | + constructor(x, y, side) { |
| 14 | + super(x, y, side, side); |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +const serializable = Category => class extends Category { |
| 19 | + toString() { |
| 20 | + return `[${this.x}, ${this.y}, ${this.width}, ${this.height}]`; |
| 21 | + } |
| 22 | +}; |
| 23 | + |
| 24 | +const measurable = Category => class extends Category { |
| 25 | + area() { |
| 26 | + return this.width * this.height; |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +const movable = Category => class extends Category { |
| 31 | + move(x, y) { |
| 32 | + this.x += x; |
| 33 | + this.y += y; |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +const scalable = Category => class extends Category { |
| 38 | + scale(k) { |
| 39 | + const x = this.width * k / 2; |
| 40 | + const y = this.height * k / 2; |
| 41 | + this.width += x; |
| 42 | + this.height += y; |
| 43 | + this.x -= x; |
| 44 | + this.y -= y; |
| 45 | + } |
| 46 | +}; |
| 47 | + |
| 48 | +// Utils |
| 49 | + |
| 50 | +const compose = (...fns) => arg => ( |
| 51 | + fns.reduce((arg, fn) => fn(arg), arg) |
| 52 | +); |
| 53 | + |
| 54 | +// Usage |
| 55 | + |
| 56 | +const Square1 = equilateral(serializable(measurable( |
| 57 | + movable(scalable(Rect)) |
| 58 | +))); |
| 59 | + |
| 60 | +const toSquare = compose( |
| 61 | + equilateral, serializable, measurable, movable, scalable |
| 62 | +); |
| 63 | + |
| 64 | +const Square2 = toSquare(Rect); |
| 65 | + |
| 66 | +const p1 = new Square2(10, 20, 50); |
| 67 | +p1.scale(1.2); |
| 68 | +p1.move(-10, 5); |
| 69 | +console.log(p1.toString()); |
| 70 | +console.log('Area:', p1.area()); |
0 commit comments