Express functions more simply using abs()?

60 Views Asked by At

I have 2 functions (the BLUE and RED functions defined from 0 to 4) that I think can be expressed more simply using the Math.abs() function. But I can't do it, I hope you can. Here are the functions in javascript:

  plot1(function(x) { // the BLUE function
    if (1<x && x<2) return 2-x;
    if (2<x && x<3) return 6-x;
                    return   x;
  } );   
  plot1(function(x) { // the RED function
    if (x<1) return 2-x;
    if (3<x) return 6-x;
             return   x;
  } ); 

EDIT1: I have this little improvement for the RED function:

  if (x<3) return 1 + Math.abs(x-1);
  else return 1 + Math.abs(x-5);

enter image description here

2

There are 2 best solutions below

0
On BEST ANSWER

I would like to say that I got these through keen analysis, but I must admit there was a lot of experimenting. This is what I was looking for. The % is the MOD or REMAINDER function in javascript. (Can I accept my own answer?)

  plot1(function(x) { // the RED function
    return 1 + Math.abs((x+1)%4 - 2);
  } );   

  plot1(function(x) { // the BLUE function
    return (3 + Math.abs((x+3)%4 - 2)) % 4;
  } );   
0
On

I think this would need to be defined piecewise:

If x<1, then blue = Math.abs(x)
Else if x<2, then blue = -1 * Math.abs(2-x)
Else if x<3, then blue = -1 * Math.abs(6-x)
Else blue = Math.abs(x)

Give the red function a try