Last active
September 30, 2020 16:49
-
-
Save sagar-gavhane/9fc3918d41cf2483b09e528e13b305d9 to your computer and use it in GitHub Desktop.
Polyfill of Array's map, filter and reduce methods
This file contains 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
// reduce | |
Object.defineProperty(Array.prototype, 'myReduce', { | |
value: function(fn, initial) { | |
let values = this; | |
values.forEach((item, idx) => { | |
initial = fn(initial, item, idx) | |
}) | |
return initial; | |
} | |
}) | |
// map | |
Object.defineProperty(Array.prototype, 'myMap', { | |
value: function(fn) { | |
let storage = []; | |
for (let i = 0; i < this.length; i++) { | |
storage.push(fn(this[i], i)); | |
} | |
return storage; | |
} | |
}) | |
// filter | |
Object.defineProperty(Array.prototype, 'myFilter', { | |
value: function(fn) { | |
let storage = []; | |
for (let i = 0; i < this.length; i++) { | |
if (fn(this[i], i)) { | |
storage.push(this[i]); | |
} | |
} | |
return storage; | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This snippet is created for creaking interviews but in reality, using this is polyfill is very risky so please don't use on production.