-
Notifications
You must be signed in to change notification settings - Fork 0
/
reduce.js
113 lines (84 loc) · 2.41 KB
/
reduce.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
///////////////////////
// ES6 - reduce helper
///////////////////////
/*
var numbers = [10, 20, 30];
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log('ES5 with for loop:', sum);
numbers.reduce(function(sum, number) {
return sum + number;
}, 0);
console.log(sum);
*/
// ====================================================================
/*
var primaryColors = [
{ color: 'red' },
{ color: 'yellow' },
{ color: 'blue' }
];
// use map helper
var primaryColorArrayMap = primaryColors.map(function(primaryColor) {
return primaryColor.color;
});
console.log(primaryColorArrayMap);
// use reduce helper
var primaryColorArrayReduce = primaryColors.reduce(function(previous, primaryColor) {
previous.push(primaryColor.color);
return previous;
}, []);
console.log(primaryColorArrayReduce);
*/
// ====================================================================
/*
function balancedParens(string) {
return !string.split('').reduce(function(previous, char) {
if (previous < 0) { return previous; }
if (char === '(') { return ++previous; }
if (char === ')') { return --previous; }
return previous;
}, 0);
}
console.log(balancedParens('())('));
*/
// ====================================================================
// Distance Traveled
var trips = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];
var totalDistance = trips.reduce(function(base, trip) {
return trip.distance + base;
}, 0);
console.log(totalDistance);
// => 47
///////////////////
var trips = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];
var totalDistance = trips.reduce(function(base, sum) {
return sum.distance + base;
}, 0);
console.log(totalDistance);
// => 47
///////////////////
var sum = 0;
var trips = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];
var totalDistance = trips.reduce(function(base, sum) {
return sum.distance + base;
}, 0);
console.log(totalDistance);
// => 47
// ==================================================
//Reducing Properties
var desks = [
{ type: 'sitting' },
{ type: 'standing' },
{ type: 'sitting' },
{ type: 'sitting' },
{ type: 'standing' }
];
var deskTypes = desks.reduce(function(tally, desk) {
tally[desk.type] += 1;
return tally;
}, { sitting: 0, standing: 0 });
// ==================================================
// Hardmode: Custom 'Unique' Helper