Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

Question was provided via image upload.

Question

Question was provided via image upload.

Explanation:

Identify the repeated blocks of code

The instructions ask us to find repeated blocks of code inside the event handlers for "lemon" (lines 29–56) and "lime" (lines 58–79) and replace them with a single function called moveLemon() that is declared once but called twice.

Looking closely at the code:

  • Inside the "lemon" event handler (lines 48–52):
  setProperty("lemon", "x", randomNumber(50, 220));
  setProperty("lemon", "y", randomNumber(50, 320));
  setProperty("lime", "x", randomNumber(50, 220));
  setProperty("lime", "y", randomNumber(50, 320));
  • Inside the "lime" event handler (lines 65–69):
  setProperty("lemon", "x", randomNumber(50, 220));
  setProperty("lemon", "y", randomNumber(50, 320));
  setProperty("lime", "x", randomNumber(50, 220));
  setProperty("lime", "y", randomNumber(50, 320));

These four lines are identical in both event handlers and are used to move the lemon and lime to random locations using Random Number Generation in Code.org App Lab.

Declare the new function

To refactor this code, we declare a single function named moveLemon() containing the repeated lines:

function moveLemon() {
  setProperty("lemon", "x", randomNumber(50, 220));
  setProperty("lemon", "y", randomNumber(50, 320));
  setProperty("lime", "x", randomNumber(50, 220));
  setProperty("lime", "y", randomNumber(50, 320));
}

Call the function in both event handlers

We replace the four repeated lines in both event handlers with a single call to our new function:

  • Inside the "lemon" event handler:
  // Move the lemon and lime to random locations
  moveLemon();
  • Inside the "lime" event handler:
  // Move the lemon and lime to random locations
  moveLemon();

Answer:

To refactor the code and remove the repeated blocks, follow these steps:

  1. Declare the function moveLemon() at the bottom of your workspace:
function moveLemon() {
  setProperty("lemon", "x", randomNumber(50, 220));
  setProperty("lemon", "y", randomNumber(50, 320));
  setProperty("lime", "x", randomNumber(50, 220));
  setProperty("lime", "y", randomNumber(50, 320));
}
  1. Replace the repeated lines in the "lemon" event handler (around lines 48–52) with a function call:
// Move the lemon and lime to random locations
moveLemon();
  1. Replace the repeated lines in the "lime" event handler (around lines 65–69) with a function call:
// Move the lemon and lime to random locations
moveLemon();