-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem_19.js
More file actions
101 lines (80 loc) · 2.31 KB
/
item_19.js
File metadata and controls
101 lines (80 loc) · 2.31 KB
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
// get comfortable using higher order functions
//
// Higher-order functions used to be a shibboleth of the monks of functional
// programming, an esoteric term for what seemed like an advanced programming
// technique.
//
// author uses new words:
// shibboleth - a custom, principle, or belief distinguishing a particular
// class or group of people, especially a long standing one
// regarded as outmoded or no longer important.
//
// esoteric - intended for or likely to be understood by only a small number
// of people with a specialized knowledge of interest.
//
// Simply higher order functions are functions that take other functions as
// arguments or return functions as their result.
function compareNumbers(x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
}
[3, 1, 4, 1, 5, 9].sort(compareNumbers); // [1, 1, 3, 4, 5, 9]
// alternatively
[3, 1, 4, 1, 5, 9].sort(function(x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
}); // [1, 1, 3, 4, 5, 9]
var names = ["Nick", "Anne", "Zawadi"];
var upper = [];
for (var i = 0, n = names.length; i < n; i++) {
upper[i] = names[i].toUpperCase();
}
upper;
// can be re-written
var names = ["Nick", "Anne", "Zawadi"];
var upper = names.map(function(name) {
return name.toUpperCase();
});
var aIndex = "a".charCodeAt(0); // 97
var alphabet = "";
for (var i = 0; i < 26; i++) {
alphabet += String.fromCharCode(aIndex + i);
}
alphabet; // "abcdefghijklmnopqrstuvwxyz"
var digits = "";
for (var i = 0; i < 10; i++) {
digits += i;
}
digits; // "0123456789"
var random = "";
for (var i = 0; i < 8; i++) {
random += String.fromCharCode(Math.floor(Math.random() * 26) + aIndex);
}
random; // "veqmbzln" varies with each call
function buildString(n, callback) {
var result = "";
for (var i = 0; i < n; i++) {
result += callback(i);
}
return result;
}
var alphabet = buildString(26, function(i) {
return String.fromCharCode(aIndex + i);
});
alphabet; // "abcdefghijklmnopqrstuvwxyz"
var digits = buildString(10, function(i) { return i; });
digits; // "0123456789"
var random = buildString(8, function() {
return String.fromCharCode(Math.floor(Math.random() * 26) + aIndex);
});
random; // "xvoxvyfo"