Javascript functions

To clamp the values between 0 and 15 you could use the js remainder operator ( % ).

function clamp (score) {
  return score % 16;
}

@dennisjn I thought you had something there :slight_smile:

Unfortunately it doesn’t work for the highest and lowest scores

score 100

(2 * Math.floor(100 / 10) - 3) % 16 // (17 % 16) -> 1 should be 15

score 15

(2 * Math.floor(15/ 10) - 3) % 16 // (-1 % 16) -> -1 should be 0

The modulus operator doesn’t clamp, instead it gives the remainder after division by that number.

Here is a clamp function:

const clamp = (num, min, max) => Math.min(Math.max(num, min), max);

Usage is:

const min = 0;
const max = 15;
const num1 = clamp(100, min, max); // 15
const num2 = clamp(-1, min, max); // 0

As per post #22 :slight_smile:

1 Like

Thank you for that Dennis! learning as i go along.

This is awesome. I am trying to understand the different functions. Thank you for your input. Much appreciated.

1 Like

This is fantastic. Definitely learning a lot from you. Thank you.

I have added some more comments to the codepen I posted before, which I hope are helpful.

1 Like