-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2-extends.js
More file actions
70 lines (57 loc) · 1.29 KB
/
2-extends.js
File metadata and controls
70 lines (57 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use strict';
class Rect {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
const equilateral = (Category) => class extends Category {
constructor(x, y, side) {
super(x, y, side, side);
}
};
const serializable = (Category) => class extends Category {
toString() {
return `[${this.x}, ${this.y}, ${this.width}, ${this.height}]`;
}
};
const measurable = (Category) => class extends Category {
area() {
return this.width * this.height;
}
};
const movable = (Category) => class extends Category {
move(x, y) {
this.x += x;
this.y += y;
}
};
const scalable = (Category) => class extends Category {
scale(k) {
const dx = this.width * k;
const dy = this.height * k;
this.width += dx;
this.height += dy;
this.x -= dx / 2;
this.y -= dy / 2;
}
};
// Utils
const compose = (...fns) => (arg) => (
fns.reduce((arg, fn) => fn(arg), arg)
);
// Usage
const Square1 = equilateral(serializable(measurable(
movable(scalable(Rect))
)));
const toSquare = compose(
equilateral, serializable, measurable, movable, scalable
);
const Square2 = toSquare(Rect);
const p1 = new Square2(10, 20, 50);
p1.scale(1.2);
p1.move(-10, 5);
console.log(p1.toString());
console.log('Area:', p1.area());