So I have a method that returns an object that returns referrals of a individual
function getReferredUsers(userId) {
const usersMap = {
a : ['b', 'c'],
b: ['d', 'e'],
d: ['f', 'g']
};
return usersMap[userId] || [];
}
So, in the example a directly referred b and c. While b directly referred d and e and so on.
so d and e becomes indirect referrals for a. f,g are indirect for a as d is also an indirect for a.
For direct we get 3 points for indirect we get 2.
We need to calculate total points for a.
I tried
var _opSum = 0;
function getTotalReferralBonus(userId, bonus) {
if(bonus === 0)
return 0;
let directUsers = getReferredUsers(userId);
if(directUsers.length > 0) {
for(let user of directUsers) {
_opSum = getTotalReferralBonus(user, bonus -1) + bonus;
}
}else {
_opSum += getTotalReferralBonus(userId, bonus -1);
}
return _opSum;
}
But it does not work.
What am I doing wrong ?
UPDATE
Total points that a would get is 3 + 3 (for b,c) + 2 + 2 (for d,e through b) + 1 + 1 (for f,g through d through b) = 12
dgoing toa? please add the wanted result._opSumneeds to be a local variable of the recursive function. Otherwise, that assignment in thefor ... ofloop will overwrite the previous value.