forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapFilterReducePolyfill.js
More file actions
33 lines (29 loc) · 855 Bytes
/
mapFilterReducePolyfill.js
File metadata and controls
33 lines (29 loc) · 855 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
33
const numbers = [1, 2, 3, 4, 5];
Array.prototype.customMap = function (cb) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(cb(this[i], i, this));
}
return result;
};
Array.prototype.customFilter = function (cb) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)) result.push(this[i]);
}
return result;
};
Array.prototype.customReduce = function (cb, initialValue) {
let prevValue = initialValue;
for (let i = 0; i < this.length; i++) {
if (prevValue) {
prevValue = cb(prevValue, this[i], i, this);
} else {
prevValue = this[0];
}
}
return prevValue;
};
console.log(numbers.customMap((number) => number * 2));
console.log(numbers.customFilter((number) => number > 2));
console.log(numbers.customReduce((prev, curr) => prev + curr, 0));