0

I have the following problem and I want to solve it using a specific approach:

// Write a function that takes two numbers, one representing the hour hand on a clock and the other the minute hand. determine the angle of the clock hands. if greater than 180°, return the opposing angle.

I created an object outside of the function. I want my function to access the key value pairs.

let clock = {

      // min bucket: // on clock  
      0: 12
      5: 1
      10: 2
      15: 3
      20: 4
      25: 5
      30: 6
      35: 7
      40: 8
      45: 9
      50: 10
      55: 11
      60: 12
    }

Here is my function skeleton. I cannot modify the arguments inside clockAngle.

function clockAngle (hour, minute) {




}

clockAngle(1, 15)

My issue is I have no idea (with the above function) how to do the following:

a. take the minute input argument (15) and use the clock object to set a new variable (let's say clock_num) equal to the value associated with the key of 15 which in our case is 3.

How do I do the above?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
PineNuts0
  • 4,740
  • 21
  • 67
  • 112
  • It's not clear what the issue is; if `clock` is visible in the scope of `clockAngle` then you just reference it using array notation like you'd expect. I'll point out, though, that this problem is trivially solvable using a tiny bit of math--no object like this is necessary. – Dave Newton Apr 03 '19 at 14:12

1 Answers1

0

Assuming clockAngle is declared in the same scope as clock (or a scope inside it), then clockAngle closes over clock and so clock is in scope. You can use a property accessor using brackets to access the entry in clock:

let clock_num = clock[minute];

Live Example:

let clock = {
    // min bucket: // on clock  
    0: 12,
    5: 1,
    10: 2,
    15: 3,
    20: 4,
    25: 5,
    30: 6,
    35: 7,
    40: 8,
    45: 9,
    50: 10,
    55: 11,
    60: 12
}

function clockAngle (hour, minute) {
    let clock_num = clock[minute];
    console.log(`clock_num for minute value ${minute} is ${clock_num}`);
}

clockAngle(1, 15);

More about closures in this question's answers.

More about property access with variables in this question's answers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875