Created
October 15, 2020 15:22
-
-
Save naveenrawat51/5285c36eb9272d02fefba84044d35d77 to your computer and use it in GitHub Desktop.
JavaScript map(), reduce(), filter(), forEach(), call(), apply() and bind() 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
Call(), apply() and Bind() Implementation: | |
// Bind implementation | |
Function.prototype.myBind = function(...args) { | |
let obj = this; | |
let params = args.slice(1); | |
return function(...args2) { | |
return obj.apply(args[0], [...params, ...args2]); | |
} | |
} | |
// call implementation | |
Function.prototype.myCall = function(context, ...args) { | |
context.fnName = this; | |
context.fnName(...args); | |
} | |
// apply implementation | |
Function.prototype.myApply = function(context, args) { | |
context.fnName = this; | |
context.fnName(...args); | |
} | |
map(), filter(), reduce() and forEach() Implementation: | |
// map() Implementation: | |
Array.prototype.myMap = function(callback) { | |
const result = []; | |
for(let i = 0; i < this.length; i++) { | |
result.push(callback(this[i], i, this)) | |
} | |
return result; | |
}; | |
//filter() Implementation | |
Array.prototype.myFilter = function(callback) { | |
const result = []; | |
for(let i = 0; i < this.length; i++) { | |
const eleResult = callback(this[i], i, this); | |
if(eleResult) { | |
result.push(this[i]) | |
} | |
} | |
return result; | |
}; | |
// reduce() Implementation: | |
Array.prototype.myReduce = function(callback, initialValue) { | |
let start = 0; | |
var accumulator; | |
if (initialValue) { | |
accumulator = initialValue; | |
} else { | |
accumulator = this[0]; | |
start = 1; | |
} | |
for(let i = start; i < this.length; i++) { | |
if(accumulator !== undefined) { | |
accumulator = callback(accumulator, this[i], i, this); | |
} else { | |
accumulator = this[i] | |
} | |
} | |
return accumulator; | |
}; | |
// forEach Implementation: | |
Array.prototype.myForEach = function(callback) { | |
for(let i = 0; i < this.length; i++) { | |
callback(this[i], i, this); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment