2

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

3
  • 1
    how is d going to a? please add the wanted result. Commented Jun 6, 2019 at 12:04
  • I think _opSum needs to be a local variable of the recursive function. Otherwise, that assignment in the for ... of loop will overwrite the previous value. Commented Jun 6, 2019 at 12:07
  • @NinaScholz Please see the update Commented Jun 6, 2019 at 12:12

1 Answer 1

2

You need a local variable _opSum and you need to get all bonusses from the nested Id.

function getReferredUsers(userId) {
  const usersMap = {
    a: ['b', 'c'],
    b: ['d', 'e'],
    d: ['f', 'g']
  };
  return usersMap[userId] || [];
}

function getTotalReferralBonus(userId, bonus) {
  var _opSum = 0; // local variable
  if (bonus === 0) return 0;
  let directUsers = getReferredUsers(userId);
  if (directUsers.length > 0) {
    for (let user of directUsers) {
      _opSum += getTotalReferralBonus(user, bonus - 1) + bonus; // add all instead of assignment
    }
  } else {
    _opSum += getTotalReferralBonus(userId, bonus - 1);
  }
  return _opSum;
}

console.log(getTotalReferralBonus('a', 3));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.