Implement Count By in JavaScript

 Implement a countBy function similar to lodash’s countBy.

Before you begin coding, take a moment to address these questions:

  1. What is the purpose of countBy, and how does it function?
  2. What comprehensive test cases should you write to validate that your implementation works correctly?

Once you’ve answered these, follow these steps:

  1. Code out the test cases you identified above.
  2. Implement your solution for the countBy function.
  3. Use “Run code” to demonstrate to your interviewer that your function passes the test cases you wrote in step 1.
  4. When you are confident that your solution is complete, use “Run test” to validate it against the provided test cases and ensure you haven’t missed any edge cases.
Solutioin:

Let countBy be the input function. The goal of the countBy function is to iterate over an array, apply the given iteratee function to each item, and return an object where each key is the result of the iteratee function, and the corresponding value is the count of occurrences for that key.

function countBy(array, iteratee) {
    return array.reduce((result, item) => {
        const key = iteratee(item);             // Apply the iteratee function to the item
        result[key] = (result[key] || 0) + 1;   // Increment the count for the key
        return result;                          // Return the updated result object
    }, {});                                     // Start with an empty object as the accumulator
}

No comments:

Post a Comment

Best for you