I have a set of users. I need to call "costlyEncryptionFunction" on each user.id, but I don't want to call "costlyEncryptionFunction" multiple times on the same user.id.
Here is a working example:
const costlyEncryptionFunction = async (id) => {
return new Promise((res) => {
setTimeout(() => {
res(id + 1000)
}, 1000)
})
}
let users = [
{id: 1, item: 1},
{id: 1, item: 2},
{id: 2, item: 5},
{id: 2, item: 6}
]
let currentUserId
users.map(async (user) => {
let encryptedUserId
if(!currentUserId || currentUserId != user.id){
currentUserId = user.id
encryptedUserId = await costlyEncryptionFunction(currentUserId)
}
if(encryptedUserId){
console.log(`inside: ${encryptedUserId} ${user.item} ... do more stuff` )
}
})
The output reads
inside: 1001 1 ... do more stuff
inside: 1002 5 ... do more stuff
I am trying to have my output read:
inside: 1001 1 ... do more stuff
inside: 1001 2 ... do more stuff
inside: 1002 5 ... do more stuff
inside: 1002 6 ... do more stuff
Does anyone have a solution to this, other than calling "costlyEncryptionFunction" and repeating the same userId multiple times?