Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tell me what's wrong with this code?
var userService = (function() {
// This array will store all users
var userList = [
{
id: 1,
name: 'First User',
email: 'first.user@example.com'
}
];
// Fetches a user by id
var getAction = function getAction( id ) {
var rightUser = null;
for ( var i = 0; i < userList.length; i++ ) {
if ( userList[i].id == id ) {
rightUser = userList[ i ];
}
}
return rightUser;
};
// Fetches a user by email
var getByEmailAction = function getByEmailAction( email ) {
var rightUser = null;
for ( var i = 0; i < userList.length; i++ ) {
if ( userList[i].email == email ) {
rightUser = userList[ i ];
}
}
return rightUser;
};
// Saves a user in the userList array, checks if the email already exists or not
var saveAction = function saveAction( user ) {
var userExists = false;
if ( user.id ) userExists = true;
for ( var i = 0; i < userList.length; i++ ) {
if ( userList[i].email == user.email ) {
userExists = true;
}
}
if ( ! userExists ) {
user.id = userList.length;
userList[ userList.length ] = user;
} else {
console.error( 'The user already exists! Please update the data instead.' );
}
};
// Updates a user in the userList array
var updateAction = function updateAction( user ) {
for ( var i = 0; i < userList.length; i++ ) {
var userFound = userList[ i ];
if ( userFound.id === user.id ) {
userFound.name = user.name;
userFound.email = user.email;
}
}
};
// Deletes a user in the userList array
var deleteAction = function deleteAction( id ) {
for ( var i = 0; i < userList.length; i++ ) {
if ( userList[i].id == id ) {
delete userList[i];
}
}
};
// Deletes all users
var deleteAllAction = function deleteAllAction() {
for ( var i = 0; i < userList.length; i++ ) {
delete userList[ i ];
}
};
return
{
get: getAction,
getByEmail: getByEmailAction,
save: saveAction,
update: updateAction,
delete: deleteAction,
deleteAll: deleteAllAction
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.