-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyReduce.js
More file actions
32 lines (24 loc) · 776 Bytes
/
myReduce.js
File metadata and controls
32 lines (24 loc) · 776 Bytes
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
function myReduce(array, func, initial) {
let value;
let index;
if (initial === undefined) {
value = array[0];
index = 1;
} else {
value = initial;
index = 0;
}
array.slice(index).forEach(element => value = func(value, element));
return value;
}
let smallest = (result, value) => (result <= value ? result : value);
let sum = (result, value) => result + value;
console.log(myReduce([5, 12, 15, 1, 6], smallest)); // 1
console.log(myReduce([5, 12, 15, 1, 6], sum, 10)); //49
function longestWord(words) {
return myReduce(words, longest);
}
function longest(result, currentWord) {
return currentWord.length >= result.length ? currentWord : result;
}
console.log(longestWord(['abc', 'launch', 'targets', ''])); // "targets"