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);

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?)