-
Notifications
You must be signed in to change notification settings - Fork 0
/
11_this.test.js
65 lines (53 loc) · 2.01 KB
/
11_this.test.js
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
describe("About this", () => {
it("should print the name of the person objects", () => {
const getName = function() {
return this.name;
};
const john = { name: "John" };
const boundedGetName = getName.bind(john); // was nothing
expect(boundedGetName()).toBe("John"); // USE bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
expect(getName.call(john)).toEqual("John"); // USE call https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
expect(getName.apply(john)).toEqual("John"); // USE apply https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
});
it("should set John properties in Person using this", () => {
function Person() {
// was empty
this.age = 28;
this.name = "John";
this.isFine = () => true;
}
const john = {
// was null
age: null,
name: null,
isFine: null
};
Person.call(john); // was nothing
expect(john.age).toBe(28);
expect(john.name).toEqual("John");
expect(john.isFine()).toBe(true);
});
it("should return the maximum number in an array", () => {
//don't google it, try it first! hint: use apply and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
const numbers = [1, 99, 34, 1000, 123];
expect(Math.max.apply(null, numbers)).toBe(1000);
});
it("should return the average score", () => {
const leaderBoard = {
scores: [900, 845, 809, 950],
avgScore: null,
avg: function() {
let sumOfScores = this.scores.reduce(function(prev, cur, index, array) {
return prev + cur;
});
this.avgScore = sumOfScores / this.scores.length;
}
};
const anotherleaderBoard = {
scores: [8, 10, 8, 9, 10, 9],
avgScore: null
};
leaderBoard.avg.call(anotherleaderBoard); // was nothing
expect(anotherleaderBoard.avgScore).toBe(9);
});
});