javascriptadvanced15 minutes

Refactor Complex Data Processing Function for Improved Readability and Performance

Given a verbose and inefficient JavaScript function that processes and transforms a large dataset, refactor the code to enhance readability, maintainability, and performance without altering its output.

Challenge prompt

You are provided with a JavaScript function that processes an array of user objects, performing multiple filtering, mapping, and aggregation steps in a convoluted way. Your task is to refactor this function to improve code clarity, remove redundancy, and optimize performance, while making sure the final output remains exactly the same. Avoid changing the function signature or expected data structure of the output.

Guidance

  • Analyze the original function to understand its transformation steps and output format thoroughly before refactoring.
  • Look for repeated computations that can be memoized or computed once and reused.
  • Consider leveraging modern ES6+ features such as destructuring, arrow functions, and array methods to make the code cleaner and more expressive.
  • Ensure no change in output data; use thorough testing to validate correctness after refactoring.

Hints

  • Break down large chained operations into smaller named helper functions or intermediate variables to improve readability.
  • Use 'reduce' where appropriate to combine multiple steps efficiently.
  • Avoid mutation of input data; use pure functions and immutable patterns where possible.

Starter code

function processUsers(users) {
  let result = [];
  for (let i = 0; i < users.length; i++) {
    if (users[i].isActive) {
      let user = users[i];
      let scoreSum = 0;
      for (let j = 0; j < user.scores.length; j++) {
        if (user.scores[j] > 50) {
          scoreSum += user.scores[j];
        }
      }
      if (scoreSum > 200) {
        let nameParts = user.name.split(' ');
        result.push({
          firstName: nameParts[0],
          lastName: nameParts.length > 1 ? nameParts.slice(1).join(' ') : '',
          averageScore: scoreSum / user.scores.length
        });
      }
    }
  }
  return result;
}

Expected output

[ { firstName: 'Alice', lastName: 'Smith', averageScore: 72.5 }, { firstName: 'Bob', lastName: '', averageScore: 80 } ]

Core concepts

code refactoringarray manipulationperformance optimizationfunctional programmingES6 features

Challenge a Friend

Send this duel to someone else and see if they can solve it.