A Pen by Afaq Ahmed Khan on CodePen.
Created
November 24, 2018 07:46
-
-
Save afaqahmedkhan/a5ac418d80b224e80658797e226503bd to your computer and use it in GitHub Desktop.
Functional Programming: Implement the filter Method on a Prototype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
It would teach us a lot about the filter method if we try to implement a version of it that behaves exactly like Array.prototype.filter(). It can use either a for loop or Array.prototype.forEach(). | |
Note: A pure function is allowed to alter local variables defined within its scope, although, it's preferable to avoid that as well. | |
Write your own Array.prototype.myFilter(), which should behave exactly like Array.prototype.filter(). You may use a for loop or the Array.prototype.forEach() method. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the global Array | |
var s = [23, 65, 98, 5]; | |
Array.prototype.myFilter = function(callback){ | |
var newArray = []; | |
for(let i =0; i < this.length ; i++){ | |
if(callback(this[i])){ | |
newArray.push(this[i]); | |
} | |
} | |
return newArray; | |
}; | |
var new_s = s.myFilter(function(item){ | |
return item % 2 === 1; | |
}); |
Array.prototype.myFilter = function(callback) {
const newArray = [];
// Only change code below this line
for(let i = 0; i < this.length; i++){
if(callback(this[i], i , this)){
newArray.push(this[i])
}
}
// Only change code above this line
return newArray;
};
[23, 65, 98, 5, 13].myFilter(item => item % 2) should equal [23, 65, 5, 13].
["naomi", "quincy", "camperbot"].myFilter(element => element === "naomi") should return ["naomi"].
[1, 1, 2, 5, 2].myFilter((element, index, array) => array.indexOf(element) === index) should return [1, 2, 5].
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Much cleaner code => Functional Programming: Implement the filter Method on a Prototype