Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created July 19, 2024 16:41
Show Gist options
  • Save satyam4p/7ba258634fd1854e5ae4d45fee7d338f to your computer and use it in GitHub Desktop.
Save satyam4p/7ba258634fd1854e5ae4d45fee7d338f to your computer and use it in GitHub Desktop.
javascript polyfills
/**
* Array map polyfill
* @param {*} callback
* @returns
*/
function myMap(callback) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(callback(this[i]));
}
return newArr;
}
Array.prototype.myMap = myMap;
let arr = [1, 2, 3, 4];
let newArray = arr.myMap((num) => {
return num + 1;
});
/** Array reduce polyfill */
function myReduce(callback, initialValue) {
if (typeof callback !== "function") {
throw new TypeError("callback must be a function");
}
const array = this;
const length = array.length;
let accumulator = initialValue !== undefined ? initialValue : array[0];
for (let i = 0; i < length; i++) {
if (i in array) {
accumulator = callback.call(undefined, accumulator, array[i], i, array);
}
}
}
/**
* Arrray bind function
* @param {*} context
*/
function myBind(context, ...args1) {
let fn = this;
return function (...args2) {
return fn.apply(context, [...args1, ...args2]);
};
}
Function.prototype.myBind = myBind;
function abc(num1, num2) {
return num1 + num2;
}
let basic = {
name: "test1",
num: 123,
};
let newFunc = abc.mybind(basic, "jammu");
newFunc("hello");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment