Underrated step for logic building in programming.

Image
Logic building is a crucial and complex skill in programming. In essence, it is ability to come-up with solution of coding problem and write precise instructions ( or code) that a computer can execute autonomously. This skill requires aligning your thought process with computer and its capabilities. And running through code some-what abstractly to know and predict the behavior of code before it is executed. To be able to do this, one essential step that many beginner programmers overlook is performing dry runs. Understanding Dry Runs The concept of a dry run in programming is straightforward: can you mentally execute your code and predict its output without actually running it on a computer? While this seems simple, it is a challenging task. Typically, we are taught to write code, run it, and observe the output. This cycle is essential because code needs to run to be validated. However, if you rely solely on running your code to understand its behavior, you may struggle with building

🖥️Building Custom Map Function in JavaScript Explained!🖥️

 Let's create a function that replicates the behavior of JavaScript's Array.prototype.map() method. The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. Here is how we can achieve this without using the map() method:

Plan

  1. Function Definition: Define a function customMap.
  2. Parameters: The function takes two parameters:
    • array: The array to be mapped.
    • callback: The function to execute on each element of the array.
  3. Initialize Result Array: Create an empty array to store the results.
  4. Loop Through Array: Use a for loop to iterate over each element in the input array.
  5. Apply Callback: For each element, apply the callback function and store the result in the result array.
  6. Return Result: After the loop, return the result array.

Implementation

Here's the detailed code:

/**
 * Custom implementation of the array map method.
 * @param {Array} array - The array to be mapped.
 * @param {Function} callback - The function to execute on each element.
 * @returns {Array} A new array with the results of calling the provided function on every element.
 */
function customMap(array, callback) {
    // Initialize the result array
    const result = [];

    // Loop through each element in the array
    for (let i = 0; i < array.length; i++) {
        // Apply the callback to the current element and store the result
        result.push(callback(array[i], i, array));
    }

    // Return the resulting array
    return result;
}

// Example usage
const numbers = [1, 2, 3, 4, 5];
const doubled = customMap(numbers, function(num) {
    return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]

Explanation

This code defines a function called customMap which works similarly to the built-in map method in JavaScript arrays. It transforms each element in an array by applying a given function and returns a new array with the transformed elements.

Let's break down the code step by step to understand how it works.

Code Breakdown

function customMap(array, callback) {
  • Function Definition: This line defines a function named customMap which takes two parameters:
    • array: The input array that we want to transform.
    • callback: The function that will be applied to each element of the input array.
    // Create an empty list to store the results
    const result = [];
  • Initialize Result Array: We create an empty array called result which will hold the transformed elements after applying the callback function to each element in the input array.
    // Go through each item in the input list
    for (let i = 0; i < array.length; i++) {
  • Loop Through Array: We use a for loop to iterate over each element in the input array. The loop runs from 0 to array.length - 1.

    • i is the loop counter which starts at 0 and increments by 1 in each iteration until it reaches the length of the array.
    // Apply the callback function to the current item and add the result to the result list
            result.push(callback(array[i], i, array));
    
  • Apply Callback and Store Result:

    The callback function in the customMap function is designed to accept three arguments to provide more flexibility and information to the callback function. Here’s why each of these arguments can be useful:

    1. Current Element (array[i]):
      • This is the value of the current element being processed in the array.
      • It allows the callback function to operate directly on the element, transforming or using it as needed.
    2. Index (i):
      • This is the index of the current element being processed.
      • Providing the index can be useful for operations that depend on the position of the element within the array. For example, if you need to access other elements relative to the current element, or if the transformation depends on the position (like returning the index instead of the value).
    3. Original Array (array):
      • This is the array on which customMap was called.
      • It allows the callback function to access the entire array if needed. This can be useful in cases where the transformation of an element depends on other elements in the array or where the array's properties are needed for the computation.
    • The result of the callback function is then added to the result array using the push method.
    }
    // Return the list of transformed items
    return result;
}
  • End Loop and Return Result:
    • After the loop has processed all elements in the input array, the result array now contains all the transformed elements.
    • The function returns the result array.

Example Usage

Let's see how the function can be used with an example.

const numbers = [1, 2, 3, 4, 5];

const doubled = customMap(numbers, function(num) {
    return num * 2;
});

console.log(doubled); // Output: [2, 4, 6, 8, 10]
  • We define an array numbers with values [1, 2, 3, 4, 5].
  • We call customMap with numbers and a callback function that doubles each number.
  • The customMap function processes each element in numbers using the callback and returns a new array [2, 4, 6, 8, 10] which is logged to the console.

Example: Usage of All Three Arguments

Here’s an example where all three arguments can be useful:

const numbers = [1, 2, 3, 4, 5];

const transformed = customMap(numbers, function(num, index, array) {
    // Use the element and index to create a new value
    return num + index + array.length;
});

console.log(transformed); // Output: [6, 8, 10, 12, 14]

In this example:

  • num is the current element.
  • index is the position of the current element in the array.
  • array.length is used from the original array to add to each element.

This results in each element being transformed based on its value, its position, and the length of the array, demonstrating how having access to all three arguments can be beneficial.

Comments

Popular posts from this blog

Building JavaScript Array Methods from Scratch in 2024 - Easy tutorial for beginners # 1

Build eisenhower matrix with React, firebase and neumorphism ui . (Part one)

Creating a Dynamic Search Bar in React: A Step-by-Step Tutorial