/
underscore_03.js
116 lines (72 loc) · 2.43 KB
/
underscore_03.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
113
114
115
// ------------------------------------------------------------
// Knihovna Underscore.js: demonstracni priklad cislo 3
// Pouziti funkci pro vyhledani prvku v polich.
// ------------------------------------------------------------
var names = ["C", "C++", "C#", "Java",
"Perl", "Python", "Ruby",
"JavaScript", "CoffeeScript", "Dart", "Wisp",
// prvky se opakuji
"C", "C++", "C#", "Java",
"Lua", "Clojure", "Lisp", "Forth"];
function printArrayItem(anArray, index)
{
console.log("#" + i + " = " + anArray[i]);
}
var i;
console.log("_.indexOf():");
// bezne vyhledavani prvniho prvku
i = _.indexOf(names, "Java");
printArrayItem(names, i);
// vyhledavani od desateho prvku
i = _.indexOf(names, "Java", 10);
printArrayItem(names, i);
// bezne vyhledavani neexistujiciho prvku
i = _.indexOf(names, "BASIC");
printArrayItem(names, i);
console.log("---------------------------------------");
console.log("_.lastIndexOf():");
// bezne vyhledavani posledniho prvku
i = _.lastIndexOf(names, "Java");
printArrayItem(names, i);
// vyhledavani od desateho prvku
i = _.lastIndexOf(names, "Java", 10);
printArrayItem(names, i);
// bezne vyhledavani neexistujiciho prvku
i = _.lastIndexOf(names, "BASIC");
printArrayItem(names, i);
console.log("---------------------------------------");
/* predikat vracejici true pouze v pripade, ze se v prvku
* nalezne podretezec odpovidajici regularnimu vyrazu.*/
function predicate(item)
{
return /.*Java.*/.test(item);
}
/* predikat vracejici vzdy hodnotu true */
function constantTrue(item)
{
return true;
}
/* predikat vracejici vzdy hodnotu false */
function constantFalse(item)
{
return false;
}
console.log("_.findIndex():");
i = _.findIndex(names, predicate);
printArrayItem(names, i);
i = _.findIndex(names, constantTrue);
printArrayItem(names, i);
i = _.findIndex(names, constantFalse);
printArrayItem(names, i);
console.log("---------------------------------------");
console.log("_.findLastIndex():");
i = _.findLastIndex(names, predicate);
printArrayItem(names, i);
i = _.findLastIndex(names, constantTrue);
printArrayItem(names, i);
i = _.findLastIndex(names, constantFalse);
printArrayItem(names, i);
console.log("---------------------------------------");
// ------------------------------------------------------------
// Finito
// ------------------------------------------------------------