NodeJS / Authentication: Find User by Username

Given a list of user objects, this function will take in a username and return the corresponding user object if it exists. If the user does not exist, it will return null.

Problem

Given a list of user objects, write a function that takes in a username and returns the object for that user if it exists. If the user does not exist, return null.
Example input:
const users = [
  {
    id: 1,
    username: 'jane',
    password: '123456',
  },
  {
    id: 2,
    username: 'john',
    password: 'abcdef',
  },
];
findUser('jane');
Example output:
{
  id: 1,
  username: 'jane',
  password: '123456',
}

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
const users = [
  {
    id: 1,
    username: 'jane',
    password: '123456',
  },
  {
    id: 2,
    username: 'john',
    password: 'abcdef',
  },
];

function findUser(username) {
  for (let i = 0; i < users.length; i++) {
    if (users[i].username === username) {
      return users[i];
    }
  }
  return null;
}

console.log(findUser('jane'));

/*

The solution above is optimal because it uses a for loop to iterate through the array of users.
The for loop is the most efficient way to iterate through an array.

*/

A.I. Evaluation of the Solution

The candidate's solution is correct and uses an efficient approach to solving the problem.

Evaluated at: 2022-11-23 04:17:30