javascriptintermediate10 minutes

Refactor a Complex Data Transformation Function in JavaScript

Improve the readability and maintainability of a complex JavaScript function that processes and transforms an array of user objects, ensuring the behavior remains identical.

Challenge prompt

You are given a JavaScript function that takes an array of user objects and performs multiple transformations including filtering, mapping, and sorting. The current implementation is correct but hard to read and maintain due to nested loops, repeated code, and unclear variable names. Refactor this function to improve its clarity, modularity, and efficiency without changing its output or behavior.

Guidance

  • Break down the function into smaller helper functions with meaningful names.
  • Use array helper methods like filter, map, and sort in a clear and consistent way.
  • Avoid duplicated code and magic numbers; use named constants where applicable.

Hints

  • Consider descriptive variable names that reflect the data they hold.
  • Extract filtering and mapping steps into separate functions.
  • Test the output after refactoring to ensure it remains unchanged.

Starter code

function processUsers(users) {
  let result = [];
  for (let i = 0; i < users.length; i++) {
    if (users[i].age > 18) {
      let score = users[i].points * 2;
      if (users[i].active) {
        score += 10;
      }
      result.push({
        id: users[i].id,
        name: users[i].name.toUpperCase(),
        score: score
      });
    }
  }
  for (let j = 0; j < result.length - 1; j++) {
    for (let k = 0; k < result.length - j - 1; k++) {
      if (result[k].score < result[k + 1].score) {
        let temp = result[k];
        result[k] = result[k + 1];
        result[k + 1] = temp;
      }
    }
  }
  return result;
}

Expected output

[ { id: 5, name: 'ALICE', score: 54 }, { id: 1, name: 'BOB', score: 50 }, { id: 3, name: 'JANE', score: 46 }, { id: 4, name: 'MIKE', score: 36 } ]

Core concepts

array methodsrefactoringcode readabilitymodularization

Challenge a Friend

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