Over inside user.js, we can get started by finding the user, if any. That means, we're going to use a similar technique to what we have in theĀ getUser method. I'm going to actually copy the following line from the getUser method and paste it just right inside of removeUser:
return this.users.filter((user) => user.id === id) [0]
Creating a variable called user, setting it equal to the preceding line. Now you could also go ahead and actually call getUser. I could call this.getUser, passing in id just like this:
removeUser (id) {
var user = this.getUser(id);
}
Both of those solutions are going to work as expected. Next up, if there is a user, we want to remove it, if(user), we're going to do something special, and regardless of whether or not a user did exist, we are going to return the user value:
removeUser (id) {
var user = this.getUser(id);
if (user) {
}
return user;
}
If it didn't exist we're going to return undefined, which is great, if it did exist after we remove user, we'll be returning the object, also what we want. All we need to do is figure out how to remove it from the list.
To do this, I'm going to set this.users equal to this.users, and we're going to call filter finding all users whose ID does not match the one specified up above. We're going to call filter passing in our arrow function, we're going to get the individual user, and all we're going to do inside our arrow expression syntax is add user.id does not equal id:
if (user) {
this.users = this.users.filter((user) => user.id !== id);
}
This is going to create a new array, setting it equal to this.users, and we're going to have the item removed, if any. If there was no item that's fine; this statement is never going to run and will be able to continue on returning undefined.
Now that we have this in place, we can go ahead and write a test case that makes sure it works as expected. I'm going to save user.js and right inside users.test, we're going to fill both it ('should remove a user') and it ('should not remove user') test cases. Let's get started with should remove a user.