Skip to content

Commit 57442d0

Browse files
committed
Add polyfills for map, filter and reduce
1 parent 5144b36 commit 57442d0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const numbers = [1, 2, 3, 4, 5];
2+
3+
Array.prototype.customMap = function (cb) {
4+
const result = [];
5+
for (let i = 0; i < this.length; i++) {
6+
result.push(cb(this[i], i, this));
7+
}
8+
return result;
9+
};
10+
11+
Array.prototype.customFilter = function (cb) {
12+
const result = [];
13+
for (let i = 0; i < this.length; i++) {
14+
if (cb(this[i], i, this)) result.push(this[i]);
15+
}
16+
return result;
17+
};
18+
19+
Array.prototype.customReduce = function (cb, initialValue) {
20+
let prevValue = initialValue;
21+
for (let i = 0; i < this.length; i++) {
22+
if (prevValue) {
23+
prevValue = cb(prevValue, this[i], i, this);
24+
} else {
25+
prevValue = this[0];
26+
}
27+
}
28+
return prevValue;
29+
};
30+
31+
console.log(numbers.customMap((number) => number * 2));
32+
console.log(numbers.customFilter((number) => number > 2));
33+
console.log(numbers.customReduce((prev, curr) => prev + curr, 0));

0 commit comments

Comments
 (0)