-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1_2_functions.js
executable file
·112 lines (91 loc) · 2.13 KB
/
1_2_functions.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
101
102
103
104
105
106
107
108
109
110
111
112
"use strict";
chapter("Functions");
section("dump");
const dump = function() {
for (let i = 0; i < arguments.length; i++) {
println(arguments[i]);
}
};
println("dump =", dump);
dump(1, 2, "hello", null, undefined);
println();
const dump2 = function() {
for (const arg of arguments) {
println(arg);
}
};
println("dump2 =", dump2);
dump(1, 2, "hello", null, undefined);
section("sum");
let sum = function() {
let result = 0;
for (const arg of arguments) {
result += arg;
}
return result;
};
println("sum =", sum);
example("sum(1, 2, 3)");
section("minimum");
let minimum = function() {
let result = Infinity;
for (const arg of arguments) {
if (result > arg) {
result = arg;
}
}
return result;
};
println("minimum =", minimum);
example("minimum(1, -2, 3)");
section("Named functions and arguments");
function min(a, b) {
return a < b ? a : b;
}
example("min");
example("min(1, -1)");
let m = min;
example("m(1, -1)");
example("m(1)");
example("m()");
section("Default arguments");
function def(a = -10, b = -20) {
return [a, b];
}
example("def");
example("def(1, 2)");
example("def(1)");
example("def()");
section("Rest argument and spread calls");
function minRest(first, ...rest) {
let result = first;
for (const a of rest) {
result = min(result, a);
}
return result;
}
example("minRest");
example("minRest(1)");
example("minRest(1, -1)");
example("minRest(1, -1, 2, -2)");
example("minRest(...[1, -1, 2, -2])");
example("minRest(1, -1, ...[2, -2])");
section("Arrow functions");
const minArrow = (first, ...rest) => {
let result = first;
for (const a of rest) {
result = Math.min(result, a);
}
return result;
};
example("minArrow");
example("minArrow(1)");
example("minArrow(1, -1)");
example("minArrow(1, -1, 2, -2)");
const stupidArrow = (v) => {
println(v);
// No "arguments" for arrow functions
// println(arguments);
};
example("stupidArrow");
example("stupidArrow(3)");