-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathprototype-new.js
More file actions
43 lines (35 loc) · 905 Bytes
/
prototype-new.js
File metadata and controls
43 lines (35 loc) · 905 Bytes
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
'use strict';
const validatePoint = (x, y) => {
const errors = [];
if (!Number.isFinite(x)) errors.push(new TypeError(`Invalid x: ${x}`));
if (!Number.isFinite(y)) errors.push(new TypeError(`Invalid y: ${y}`));
return errors;
};
const proto = Object.create(null);
function Point(x, y) {
const errors = validatePoint(x, y);
if (errors.length > 0) {
const cause = new AggregateError(errors, 'Validation');
throw new RangeError('Bad coordinates', { cause });
}
const self = Object.create(proto);
self.x = x;
self.y = y;
return self;
}
proto.clone = function () {
return new Point(this.x, this.y);
};
proto.move = function (x, y) {
this.x += x;
this.y += y;
};
proto.toString = function () {
return `(${this.x}, ${this.y})`;
};
// Usage
const p1 = new Point(10, 20);
console.log(p1.toString());
const c1 = p1.clone();
c1.move(-5, 10);
console.log(c1.toString());