Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created August 1, 2023 07:03
Show Gist options
  • Select an option

  • Save carefree-ladka/0ab1ddaaf1c04a7d836e642b327721f5 to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/0ab1ddaaf1c04a7d836e642b327721f5 to your computer and use it in GitHub Desktop.
Bind, Apply, Call, Map, Filter and Reduce Polyfills
Function.prototype.myBind = function (scope, ...args) {
scope.fn = this;
return function () {
return scope.fn(...args);
};
};
Function.prototype.myApply = function (scope, args) {
scope.fn = this;
return scope.fn(...args);
};
Function.prototype.myCall = function (scope, ...args) {
scope.fn = this;
return scope.fn(...args);
};
Array.prototype.myMap = function (cb) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(cb(this[i], i, this));
}
return newArr;
};
Array.prototype.myFilter = function (cb) {
let tempArr = [];
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)) {
tempArr.push(this[i]);
}
}
return tempArr;
};
Array.prototype.myReduce = function (cb, intialValue) {
var acc = intialValue;
for (let i = 0; i < this.length; i++) {
acc = acc ? cb(acc, this[i], i, this) : this[i];
}
return acc;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment