Created
September 10, 2022 11:27
-
-
Save srsandy/94e77743f505e26ea8b5fd8a9f0c7d1e to your computer and use it in GitHub Desktop.
Polyfills
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
// map | |
Array.prototype.myMap = function (cb) { | |
const results = []; | |
for (let i = 0; i < this.length; i++) { | |
results[i] = cb(this[i], i, this); | |
} | |
return results; | |
}; | |
// filter | |
Array.prototype.myFilter = function (cb) { | |
const results = []; | |
for (let i = 0; i < this.length; i++) { | |
const isTrue = cb(this[i], i, this); | |
if (isTrue) { | |
results.push(this[i]); | |
} | |
} | |
return results; | |
}; | |
// reduce | |
Array.prototype.myReduce = function (cb, iv) { | |
let acc = iv || undefined; | |
for (let i = 0; i < this.length; i++) { | |
if (acc) { | |
acc = cb(acc, this[i], i, this); | |
} else { | |
acc = this[i]; | |
} | |
} | |
return acc; | |
}; | |
// call | |
Function.prototype.myCall = function (context, ...args) { | |
const currentContext = context || window || globalThis; | |
currentContext.fn = this; | |
const res = currentContext.fn(...args); | |
delete currentContext.fn; | |
return res; | |
}; | |
// apply | |
Function.prototype.myApply = function (context, args) { | |
const currentContext = context || window || globalThis; | |
currentContext.fn = this; | |
const res = currentContext.fn(args); | |
delete currentContext.fn; | |
return res; | |
}; | |
// bind | |
Function.prototype.myBind = function (context, ...args) { | |
const currentContext = context || window || globalThis; | |
const _this = this; | |
return function (..a) { | |
_this.call(currentContext, ...[...args, ...a] ); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment