Practice - code this logic

In this exercise, we are going to:

  • understand the requirements provided by a product manager
  • write the pseudocode for it
  • sketch the flow on paper
  • code the logic

The aim is to use communication (words) and visual aids to help you and others understand the code you plan to write. And then execute that plan!

The task: calculate an employee’s bonus

The logic is to determine whether an employee should earn a bonus on top of their salary. Our team product owner has given us this description:

Calculate the bonus for an employee based on their pay grade and performance rating.

  1. If the employee's pay grade is less than 3, the bonus is 20% of their salary.
  2. If the employee's pay grade is 3, 4, 5, or 6, and their performance rating is 1, the bonus is 10% of their salary in addition to any existing bonus.
  3. If the employee's pay grade is 3, 4, 5, or 6, and their performance rating is 2, the bonus is 90% of their salary in addition to any existing bonus.
  4. If the employee's pay grade is less than 5, the bonus is 50% of their salary in addition to any existing bonus.
  5. If the employee's pay grade is between 5 and 7 (inclusive), the bonus is 40% of their salary in addition to any existing bonus.
  6. If the employee's pay grade is 7 or higher, the bonus is 10% of their salary.

Calculate the total bonus based on the above rules.

Try write the pseudocode and sketch it before reading further...

Here is the completed pseudocode


// If paygrade is less than 3
    // bonus is salary x 0.2
// Else if paygrade is equal to or greater than 3, and less than 7
    // If paygrade is < 5, bonus is salary multiplied by 0.5
    // Else bonus is salary x 0.4
    // If the performance rating is 1, bonus is any existing bonus plus salary x 0.1
    // Else if the performance rating is 2, bonus is any existing bonus plus salary x 0.9
// Else salary bonus is salary x 0.1

STEP 2: Now, code it

There are a few ways of writing these if statements, and it is intentionally a bit confusing. It’s the kind of thing you would receive from a manager or product owner. The trick is to make it as readable and as easy to follow as possible.

The logic will be the body of a function, which receives salary, pay grade and a perfomance rating as arguments. You can copy and paste this as a starting point:

function calculateBonus(salary, paygrade, rating){
	  // Add your logic here.
}

// TESTS - Run these in your browser to see if your solution works.
calculateBonus(100, 4, 1); // 60
calculateBonus(100, 4, 2); // 140
calculateBonus(100, 8, 2) // 10
calculateBonus(100, 1) // 20
calculateBonus(100, 6, 2) // 130

Links & Resources