Create Polyfils for array methods map,reduce,filter

Create Polyfils for array methods map,reduce,filter

Ā·

4 min read

Rewriting JavaScript: The Fun World of Polyfills for map, filter, and reduce šŸŒŸ

JavaScript's array methods like map, filter, and reduce are like the Swiss Army knives of coding. But what if they didnā€™t exist? Imagine coding in a world where you had to create these functionalities from scratch. šŸ˜± Donā€™t panic! Letā€™s walk through how to build these essential tools with polyfillsā€”a way to add modern features to older environmentsā€”while keeping things fun and engaging. šŸŽ‰


Polyfill for map: Mapping Our Way to Glory šŸ—ŗļø

The map function transforms each element in an array based on a callback function. Hereā€™s how we can create our own myMap method:

Code for myMap

Array.prototype.myMap = function (cb) {
    let temp = []
    for (let i = 0; i < this.length; i++) {
        temp.push(cb(this[i], i, this)) // Apply the callback and push the result
    }
    return temp;
}

const nums = [1, 2, 3, 4];
const ans = nums.myMap((num, i, arr) => num * 3); // Multiply each number by 3
console.log(ans); // Output: [3, 6, 9, 12]

Whatā€™s Happening? šŸ”

The myMap method loops through the array, applies the callback function to each element, and collects the transformed values in a new array. Itā€™s like giving every element a makeover! šŸ’…


Polyfill for filter: Sifting Out the Unwanted šŸ”

The filter function is your array's personal bouncerā€”it keeps only the elements that pass a given test. Letā€™s create our own myFilter:

Code for myFilter

Array.prototype.myFilter = function (cb) {
    let temp = []
    for (let i = 0; i < this.length; i++) {
        if (cb(this[i], i, this)) { // Check if the callback returns true
            temp.push(this[i])
        }
    }
    return temp;
}

const ans2 = nums.myFilter((num, i, arr) => num > 2); // Keep numbers greater than 2
console.log(ans2); // Output: [3, 4]

Whatā€™s Happening? šŸ”

myFilter loops through the array, tests each element against the callback, and collects only those that pass. It's like a talent show where only the best make it through! šŸŽ¤


Polyfill for reduce: Reducing to the Essence šŸŒŠ

The reduce function boils an array down to a single value, like summing numbers or merging objects. Here's how to build myReduce:

Code for myReduce

Array.prototype.myReduce = function (cb, initialValue) {
    let accumulator = initialValue;
    for (let i = 0; i < this.length; i++) {
        accumulator = accumulator ? cb(accumulator, this[i], i, this) : this[i]; // Accumulate values
    }
    return accumulator;
}

const ans3 = nums.myReduce((acc, curr, i, arr) => acc + curr, 0); // Sum all numbers
console.log(ans3); // Output: 10

Whatā€™s Happening? šŸ”

myReduce starts with an initial value (or the first array element if none is provided) and repeatedly applies the callback, accumulating the result. Itā€™s like rolling a snowball down a hillā€”it keeps getting bigger! ā˜ƒļø


Putting It All Together: A Practical Example šŸŽ“

Letā€™s combine these polyfills to solve a real-world problem. We have a list of students and need to:

  1. Filter students with marks greater than 70.

  2. Add 2 bonus marks to the filtered studentsā€™ marks.

Hereā€™s the code:

Code for Student Filtering and Mapping

let students = [
    { name: 'John', age: 20, marks: 90 },
    { name: 'Jane', age: 18, marks: 73 },
    { name: 'Chris', age: 27, marks: 68 },
];

const res = students
    .filter((stu) => stu.marks > 70) // Filter students with marks > 70
    .map((stu) => stu.marks + 2); // Add 2 bonus marks

console.log(res); // Output: [92, 75]

Why Polyfills Matter šŸ§ 

Polyfills not only make older browsers or environments compatible with modern features but also deepen your understanding of how these methods work. By writing them yourself, you learn to appreciate JavaScriptā€™s array methods and gain the skills to solve complex problems creatively.


A Fun Wrap-Up šŸ„³

Creating polyfills is like playing LEGO: you build cool stuff from scratch while learning how things work. With myMap, myFilter, and myReduce in your toolkit, you can handle arrays like a proā€”even in environments that donā€™t natively support these features.

Next time youā€™re using map, filter, or reduce, give your JavaScript engine a virtual high-fiveā€”itā€™s doing a lot of heavy lifting so you donā€™t have to! šŸ™Œ

Ā