First, Unshift adds elements to the beginning of an array.
Next, To make it more clear I have changed cb to callback so callback in this case is a function that you pass to the map/filter/reduce function. This callback function is called whenever necessary from within the map/filter/reduce functions passing necessary respective parameters.
So, in this case. I am passing in a function which takes a value and current index of an element (what actual map function does too) and returns 2 * value. Whatever this callback function returns, is stored into the array called mappedArray and finally that is returned.
I hope I am clear. Let me know if you have any doubts on that.
Girish Patil
Full-stack engineer
A quick run here. This is not foolproof though. I might be missing many things here. You can invest more time and improvise this. But this might give you the basic idea. Anyways its always better to use the native functions as they are much more optimised and cover many edge cases.
JSFiddle link https://jsfiddle.net/theevilhead/cpnsbwt4/
const values = [2, 3, 4, 7, 41, 22]; // Custom map Array.prototype.customMap = function(callback) { const mappedArray = []; for (var i = (this.length - 1); i >= 0; i--) { mappedArray.unshift(callback(this[i], i)); } return mappedArray; } const ma = values.customMap((val, index) => 2 * val) console.log("Map", ma) // Custom filter Array.prototype.customFilter = function(callback) { const filteredArray = []; for (var i = (this.length - 1); i >= 0; i--) { callback(this[i]) && filteredArray.push(this[i]) } return filteredArray } const fa = values.customFilter(val => { return (val > 5) }) console.log("Filter", fa) // Custom reduce Array.prototype.customReduce = function( callback ) { let acc = 0; const arrLength = this.length; for (var i = 0; i < arrLength; i++) { acc = callback(acc, this[i], i, this); } return acc; } const ra = values.customReduce((acc, curVal, curInd, srcArr) => { return acc + curVal }); console.log("Reduce", ra)