userRepository.getById(2) if the data source contains users with ids 1 and 2?class UserRepository { constructor() { this.users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; } getById(id) { return this.users.find(user => user.id === id); } } const userRepository = new UserRepository(); console.log(userRepository.getById(2));
getById method searches the array.The getById method uses Array.find to locate the user with the matching id. Since user with id 2 exists, it returns that user object.
addUser that adds a user object to the internal array users?class UserRepository {
constructor() {
this.users = [];
}
// Define addUser method here
}In a class, methods are defined without the = or arrow syntax. Option D uses the correct method syntax with parentheses and curly braces.
Option D uses arrow function syntax which is invalid as a class method declaration. Option D has invalid arrow function syntax. Option D is missing a semicolon but that is allowed in JavaScript, so it would also work but is less standard.
removeUser if called with an id that does not exist in the users array?class UserRepository { constructor() { this.users = [{ id: 1, name: 'Alice' }]; } removeUser(id) { const index = this.users.findIndex(user => user.id === id); this.users.splice(index, 1); } } const repo = new UserRepository(); repo.removeUser(2);
findIndex return if no match is found?findIndex returns -1 if no matching element is found. Calling splice(-1, 1) removes the last element in the array. But since the array has only one user with id 1, calling removeUser(2) will remove the last user incorrectly.
However, in JavaScript, splice(-1, 1) removes the last element, so it does remove user with id 1, which is wrong behavior.
Therefore, the correct answer is that it removes user with id 1, which is option A.
repo.users?class UserRepository { constructor() { this.users = []; } addUser(user) { this.users.push(user); } clearUsers() { this.users = []; } } const repo = new UserRepository(); repo.addUser({ id: 1, name: 'Alice' }); repo.addUser({ id: 2, name: 'Bob' }); repo.clearUsers(); repo.addUser({ id: 3, name: 'Charlie' });
clearUsers does to the users array.The clearUsers method resets the users array to an empty array. After clearing, only the last added user remains in the array.
The repository pattern abstracts data access logic from the rest of the app. This separation makes the code cleaner, easier to maintain, and easier to test by isolating database operations.
Options B, C, and D describe unrelated or incorrect benefits.