Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80684 views
1
$(document).ready(function() {
2
3
module("Chaining");
4
5
test("chaining: map/flatten/reduce", function() {
6
var lyrics = [
7
"I'm a lumberjack and I'm okay",
8
"I sleep all night and I work all day",
9
"He's a lumberjack and he's okay",
10
"He sleeps all night and he works all day"
11
];
12
var counts = _(lyrics).chain()
13
.map(function(line) { return line.split(''); })
14
.flatten()
15
.reduce(function(hash, l) {
16
hash[l] = hash[l] || 0;
17
hash[l]++;
18
return hash;
19
}, {}).value();
20
ok(counts['a'] == 16 && counts['e'] == 10, 'counted all the letters in the song');
21
});
22
23
test("chaining: select/reject/sortBy", function() {
24
var numbers = [1,2,3,4,5,6,7,8,9,10];
25
numbers = _(numbers).chain().select(function(n) {
26
return n % 2 == 0;
27
}).reject(function(n) {
28
return n % 4 == 0;
29
}).sortBy(function(n) {
30
return -n;
31
}).value();
32
equals(numbers.join(', '), "10, 6, 2", "filtered and reversed the numbers");
33
});
34
35
test("chaining: reverse/concat/unshift/pop/map", function() {
36
var numbers = [1,2,3,4,5];
37
numbers = _(numbers).chain()
38
.reverse()
39
.concat([5, 5, 5])
40
.unshift(17)
41
.pop()
42
.map(function(n){ return n * 2; })
43
.value();
44
equals(numbers.join(', '), "34, 10, 8, 6, 4, 2, 10, 10", 'can chain together array functions.');
45
});
46
47
});
48
49