flowforfrank / webtips

https://webtips.dev
1 stars 0 forks source link

webtips/javascript/how-to-clamp-numbers-in-javascript #11

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

How to Clamp Numbers in JavaScript - Weekly Webtips

You can clamp numbers in JavaScript between a min and max value, using a combination of Math.min, and Math.max.

https://www.webtips.dev/webtips/javascript/how-to-clamp-numbers-in-javascript

eviathan commented 2 years ago

If you are writing code that is in effect the sum of two if statements and it needs a whole article explaining it then you are doing something entirely stupid.

devsydungo commented 2 years ago

My own version of this:

const clamp = (a,b,c) => (a<c?(a<b?(b<c?b:c):a):(a>b?(b>c?b:c):a))

where it acts the same way it were but it accepts min and max on either of the sides

eviathan commented 2 years ago

@devsydungo The only situation I could think of where you would need that is if you don't have control over the min and max values. i.e. they are variable. In which case why would you limit those to be 2 values?

This is probably one of the few places where function composition/ currying isn't more trouble than its worth but heres a "curryless" alternative without sacrificing legibility. That said I probably wouldn't write it in nested terneries either because even that is unnecessary.

const clamp = (value, min, max) => value > min ? value < max ? value : max : min;

const clampSet = (value, ...set) => { const sortedSet = set.sort((a, b) => a - b); const min = sortedSet[0]; const max = sortedSet[set.length - 1];

return clamp(value, min, max); }

// Use clampSet(100, 1, 2 80, 90)

eviathan commented 2 years ago

Edit: Sorry I forgot it supported markdown

const clamp = (value, min, max) => value > min ? value < max ? value : max : min;

const clampSet = (value, ...set) => {
    const sortedSet = set.sort((a, b) => a - b);
    const min = sortedSet[0];
    const max = sortedSet[set.length - 1];

    return clamp(value, min, max);
}

// Use
clampSet(100, 1, 2 80, 90)