对象

To the book page

A vector type

封装一个类,实现坐标的加减法,以及get属性的length返回坐标离原点的距离。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Your code here.
class Vec{
constructor(x,y){
this.x = x;
this.y = y;
}
plus(other){
return new Vec(this.x+other.x,this.y+other.y);
}
minus(other){
return new Vec(this.x-other.x,this.y-other.y);
}
get length(){
return Math.sqrt(this.x**2+this.y**2);
}
}
console.log(new Vec(1, 2).plus(new Vec(2, 3)));
// → Vec{x: 3, y: 5}
console.log(new Vec(1, 2).minus(new Vec(2, 3)));
// → Vec{x: -1, y: -1}
console.log(new Vec(3, 4).length);
// → 5

Groups

封装一个Group类,实现相当于Set的功能。

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
class Group {
// Your code here.
constructor(){
this.members = [];
}
add(value){
if(!this.has(value)){
this.members.push(value);
}
}
delete(value){
this.members = this.members.filter(member => member!==value);
}
has(value){
return this.members.includes(value);
}
static from(iterable){
let group = new Group();
for(let value of iterable){
group.add(value);
}
return group;
}

}

let group = Group.from([10, 20]);
console.log(group.has(10));
// → true
console.log(group.has(30));
// → false
group.add(10);
group.delete(10);
console.log(group.has(10));
// → false

Iterable groups

让上面的数组类可迭代。

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
// Your code here (and the code from the previous exercise)
class Group {
// Your code here.
constructor(){
this.members = [];
}
add(value){
if(!this.has(value)){
this.members.push(value);
}
}
delete(value){
this.members = this.members.filter(member => member!==value);
}
has(value){
return this.members.includes(value);
}
static from(iterable){
let group = new Group();
for(let value of iterable){
group.add(value);
}
return group;
}
[Symbol.iterator](){
let index = 0;
let members = this.members;
return {
next(){
if(index < members.length){
return {value:members[index++],done:false};
}else {
return {done:true};
}
}
};
}
}
for (let value of Group.from(["a", "b", "c"])) {
console.log(value);
}
// → a
// → b
// → c