Created
August 1, 2023 07:03
-
-
Save carefree-ladka/0ab1ddaaf1c04a7d836e642b327721f5 to your computer and use it in GitHub Desktop.
Bind, Apply, Call, Map, Filter and Reduce Polyfills
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
| 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