-
Notifications
You must be signed in to change notification settings - Fork 0
/
functionalConcepts.js
54 lines (38 loc) · 1.05 KB
/
functionalConcepts.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
// map
const mockedArray = [1, 2, 3, 4];
function myOwnMap(func, arr) {
const mapArr = [];
for(let i = 0; i < arr.length; i++) {
const result = func(arr[i], i, arr);
mapArr.push(result);
}
return mapArr;
}
const square2 = myOwnMap(num => num ** 2, mockedArray);
console.log(square2);
// filter
function myOwnFilter(func, arr) {
const filterArr = [];
for(let i = 0; i < arr.length; i++) {
const res = func(arr[i], i, arr);
if (res) {
filterArr.push(arr[i]);
}
}
return filterArr;
}
const odd2 = myOwnFilter(num => num % 2 === 0, mockedArray);
console.log(odd2);
//reduce
function myOwnReduce(reducer, initialValue, arr) {
let accumulator = initialValue;
for(let i = 0; i < arr.length; i++) {
accumulator = reducer(accumulator, arr[i], i, arr);
}
return accumulator;
}
const sumReducer = (accumulator, currentValue) => {
return accumulator + currentValue;
}
const sum2 = myOwnReduce(sumReducer, 0, mockedArray);
console.log(sum2);