Hope everyone is having a good Christmas.
First of all, this is working code in a production environment.
I recently wrote some code for work.
The goal is to find users that contain more than one role. On the frontend, if a user has more than one role, the person using the program will see a message suggesting that they remove one of these roles.
Here is the code that I wrote. Mind you, I have changed some of the values so that anything sensitive is removed:
usersWithMultipleRoles() {
/**
* Make a flat map of all the users from each role.
* Each entry is an object with a roleId
*/
const users = this.roles.flatMap(r => {
return r.users.map(value => {
return { roleId: r.id, user: value }
})
})
/**
* Use reduce to create an array of objects.
* Each object is keyed by the user's ID,
* and its value is the roles that each user is in.
*/
const lookup = users.reduce((acc, value) => {
acc[value.user.id] = acc[value.user.id] || []
acc[value.user.id].push(value.roleId)
return acc
}, [])
/**
* Finally, return an array of users that have
* multiple roles.
*/
const usersWithManyRoles = []
lookup.forEach((value, key) => {
if (value.length > 1) {
usersWithManyRoles.push({
userId: key,
userInfo: users.find(value => value.user.id === key).user,
roles: value,
})
}
})
return usersWithManyRoles
},
The following is what I would expect if a user has more than one role assigned.
[
{
userId: 127,
userInfo: { User Object },
roles: [2, 6],
},
...
]
Just so you know, there is nothing wrong with this code. It returns exactly what I'm looking for.
What I would change
The only thing I can think about changing is the structure of the response from the first mapping function, the flatMap function.
My question to you
How would you write this function? How can I improve it? And what should I read to make better functions in the future?