Skip to content

Commit f913521

Browse files
authored
Merge pull request #12 from adwaithks/javascript-qna
Adding polyfills for Higher Order Functions in javascript - map(), filter() and reduce()
2 parents cfcea5d + 5870695 commit f913521

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

Javascript Polyfills/customFilter.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// polyfill for filter() method
2+
3+
Array.prototype.customFilter = function(callback) {
4+
let arr = this;
5+
let result = [];
6+
for (let i = 0; i < arr.length; i ++) {
7+
if(callback(arr[i])) result.push(arr[i]);
8+
}
9+
return result;
10+
}
11+
12+
// usage
13+
14+
let array = [1,2,3,4,5];
15+
let evenNumbers = array.customFilter((num) => {
16+
return num % 2 == 0;
17+
});
18+
console.log(evenNumbers); // [2, 4]

Javascript Polyfills/customMap.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// polyfill for map() method
2+
3+
Array.prototype.customMap = function(callback) {
4+
let arr = this;
5+
let result = [];
6+
for (let i = 0; i < arr.length; i ++) {
7+
result.push(callback(arr[i], i, arr));
8+
}
9+
return result;
10+
}
11+
12+
// usage
13+
14+
let array = [1,2,3,4,5];
15+
let twiceOfEachNumber = array.customMap((num) => {
16+
return num * 2;
17+
});
18+
console.log(twiceOfEachNumber); // [2, 4, 6, 8, 10]

Javascript Polyfills/customReduce.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// polyfill for reduce() method
2+
3+
Array.prototype.customReduce = function(fn, initialValue = null) {
4+
let array = this;
5+
let index = initialValue ? 0 : 1;
6+
let accumulator = initialValue ? initialValue : array[0];
7+
for (let i = index; i < array.length; i ++) {
8+
accumulator = fn(accumulator, array[i]);
9+
}
10+
return accumulator;
11+
}
12+
13+
// usage
14+
15+
let array = [1,2,3,4,5];
16+
let sum = array.customReduce((acc, num) => {
17+
return acc + num;
18+
});
19+
console.log(sum); // 15

0 commit comments

Comments
 (0)