Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Last active September 30, 2020 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar-gavhane/9fc3918d41cf2483b09e528e13b305d9 to your computer and use it in GitHub Desktop.
Save sagar-gavhane/9fc3918d41cf2483b09e528e13b305d9 to your computer and use it in GitHub Desktop.
Polyfill of Array's map, filter and reduce methods
// 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;
}
})
@sagar-gavhane
Copy link
Author

This snippet is created for creaking interviews but in reality, using this is polyfill is very risky so please don't use on production.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment