-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctional.js
More file actions
84 lines (70 loc) · 2.02 KB
/
Copy pathfunctional.js
File metadata and controls
84 lines (70 loc) · 2.02 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
let states = ["Kansas", "Nebraska", "North Dakota", "South Dakota"];
// Returns a URL-friendly version of a string.
// Example "North Dakota" -> "north-dakota"
function urlify(string) {
return string.toLowerCase().split(/\s+/).join("-");
}
// Kansas -> kansas
// North Dakota -> north-dakota
// urls: Imperative version
function imperativeUrls(elements) {
let urls = [];
elements.forEach(function(element) {
urls.push(urlify(element));
});
return urls;
}
console.log(imperativeUrls(states));
// URL: Functional version
function functionalUrls(elements) {
return elements.map(element => urlify(element));
}
console.log(functionalUrls(states));
// singles: Imperative version
function imperativeSingles(elements) {
let singles = [];
elements.forEach(function(element) {
if (element.split(/\s+/).length === 1) {
singles.push(element);
}
});
return singles;
}
console.log(imperativeSingles(states));
// singles: Functional version
function functionalSingles(elements) {
return elements.filter(element => element.split(/\s+/).length === 1);
}
console.log(functionalSingles(states));
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// sum: Imperative solution
function imperativeSum(elements) {
let total = 0;
elements.forEach(function(n) {
total += n;
});
return total;
}
console.log(imperativeSum(numbers));
// sum: Functional solution
function functionalSum(elements) {
return elements.reduce((total, n) => { return total += n; });
}
console.log(functionalSum(numbers));
// lengths: Imperative solution
function imperativeLengths(elements) {
let lengths = {};
elements.forEach(function(element) {
lengths[element] = element.length;
});
return lengths;
}
console.log(imperativeLengths(states));
// lengths: Functional solution
function functionalLengths(elements) {
return elements.reduce((lengths, element) => {
lengths[element] = element.length;
return lengths;
}, {});
}
console.log(functionalLengths(states));