简体   繁体   中英

How can I convert this if statement to an arrow function?

I have an function with an if statement that says:

function reflect() {
    if (number_a >= 600) {
         ball_velocity_a = -ball_velocity_a }
    if (number_b >= 600) {
         ball_velocity_b = -ball_velocity_b
}}

and I'm trying to convert this function into arrow function

const deflect = () => number_a >= 600 ? ball_velocity_a = -ball_velocity_a : 

but I'm not sure what to put after the : as ball_velocity_b is conditioned with number_b instead of number_a . I'm really new to arrow functions and would appreciate some help on this.

var deflect = () => { 
ball_velocity_a = number_a >= 600 ? -ball_velocity_a : ball_velocity_a;
ball_velocity_b = number_b >= 600 ? -ball_velocity_b : ball_velocity_b;
};

You could use the comma operator to chain conditions, also as you don't have an else branch it doesnt make sense to use a ternary. Here is the code that is equal to your function:

 const deflect = () => (
   number_a >= 600 && (ball_velocity_a = -ball_velocity_a),
   number_b >= 600 && (ball_velocity_b = -ball_velocity_b),
   undefined
 );

But IMO that is actually way worse than your original function.

I would try to avoid the use of globals, hard-coded constants inside helper functions and misleading function names (calling reflect/deflect if no reflect/deflect actually occurs).

const adjustVelocityComponent = (velocity, position, maxPosition) => {
  if (position >= maxPosition) // probably also check if position <= 0
    return -velocity;
  return velocity;
};

ball_velocity_a = adjustVelocityComponent(ball_velocity_a, number_a, 600);
ball_velocity_b = adjustVelocityComponent(ball_velocity_b, number_b, 600);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM