forked from mrdavidlaing/javascript-koans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAboutFunctions.js
100 lines (75 loc) · 2.37 KB
/
AboutFunctions.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
describe("About Functions", function() {
it("should declare functions", function() {
function add(a, b) {
return a + b;
}
expect(add(1, 2)).toBe(FILL_ME_IN);
});
it("should know internal variables override outer variables", function () {
var message = "Outer";
function getMessage() {
return message;
}
function overrideMessage() {
var message = "Inner";
return message;
}
expect(getMessage()).toBe(FILL_ME_IN);
expect(overrideMessage()).toBe(FILL_ME_IN);
expect(message).toBe(FILL_ME_IN);
});
it("should have lexical scoping", function () {
var variable = "top-level";
function parentfunction() {
var variable = "local";
function childfunction() {
return variable;
}
return childfunction();
}
expect(parentfunction()).toBe(FILL_ME_IN);
});
it("should use lexical scoping to synthesise functions", function () {
function makeMysteryFunction(makerValue)
{
var newFunction = function doMysteriousThing(param)
{
return makerValue + param;
};
return newFunction;
}
var mysteryFunction3 = makeMysteryFunction(3);
var mysteryFunction5 = makeMysteryFunction(5);
expect(mysteryFunction3(10) + mysteryFunction5(5)).toBe(FILL_ME_IN);
});
it("should allow extra function arguments", function () {
function returnFirstArg(firstArg) {
return firstArg;
}
expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);
function returnSecondArg(firstArg, secondArg) {
return secondArg;
}
expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);
function returnAllArgs() {
var argsArray = [];
for (var i = 0; i < arguments.length; i += 1) {
argsArray.push(arguments[i]);
}
return argsArray.join(",");
}
expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
});
it("should pass functions as values", function () {
var appendRules = function (name) {
return name + " rules!";
};
var appendDoubleRules = function (name) {
return name + " totally rules!";
};
var praiseSinger = { givePraise: appendRules };
expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);
praiseSinger.givePraise = appendDoubleRules;
expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);
});
});