Last active
October 26, 2018 19:29
-
-
Save islam3zzat/037a62c6023e817f68ae8413c5d5c029 to your computer and use it in GitHub Desktop.
This is an error prone code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function userByMatcher({ key, value }) { | |
return user => user[key] === value; | |
} | |
function updateUserName(user, { firstName, lastName }) { | |
// <~ #1 mutating argument, bad idea | |
if (firstName) user.name.firstName = firstName; | |
if (lastName) user.name.lastName = lastName; | |
return user; | |
} | |
function saveUser(users, user) { | |
for (let i = 0; i < users.length - 1; i += 1) { | |
if (users[i].id === user.id) { | |
// <~ #2 mutating argument, bad idea | |
users[i] = user; | |
return users; | |
} | |
} | |
return users; | |
} | |
let users = [ | |
{ id: 1, name: { firstName: 'Tuyet', lastName: 'Celestine' } }, | |
{ id: 2, name: { firstName: 'Keila', lastName: 'Fritsch' } }, | |
{ id: 3, name: { firstName: 'Sid', lastName: 'Dino' } }, | |
{ id: 4, name: { firstName: 'Rosalva', lastName: 'Sligh' } }, | |
]; | |
const user = users.find(userByMatcher({ key: 'id', value: 2 })); | |
const updatedUser = updateUserName(user, {lastName: 'new last name'}) | |
// no need to call `saveUser` user has already been saved :( | |
// check users | |
console.log(users) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment