// ** Very frequently asked question **
// // Reduce is important among all
// Write custom polyfill for map, reduce, filter, every ?
Array.prototype.myMap = function(callback) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
Array.prototype.myFilter = function(callback) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
Array.prototype.myReduce = function(callback, initialValue) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
let accumulator = initialValue !== undefined ? initialValue : this[0];
const startIndex = initialValue !== undefined ? 0 : 1;
for (let i = startIndex; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
Array.prototype.myEvery = function(callback) {
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
for (let i = 0; i < this.length; i++) {
if (!callback(this[i], i, this)) {
const arr = [1, 2, 3, 4, 5];
const doubled = arr.myMap(x => x * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
const evenNumbers = arr.myFilter(x => x % 2 === 0);
console.log(evenNumbers); // [2, 4]
const sum = arr.myReduce((acc, curr) => acc + curr, 0);
const allPositive = arr.myEvery(x => x > 0);
console.log(allPositive); // true