22
1
Imagine this short function to clamp a number between 0 and 255:
c = n => n > 0 ? n < 255 ? n : 255 : 0
Is this the shortest possible version of a clamp function with JavaScript (without ES.Next features)?
P.S: Not sure if it's relevant but, the 0 and 255 are not random, the idea is to clamp a number as an 8-bit unsigned integer.
2Hi and welcome to PPCG! Just to be clear, any answer you receive here will not necessarily be a good idea to use in anything except for code golfing. Aside from that, if you care about what version / environment it has to work in you might want to specify it. – FryAmTheEggman – 2019-03-05T23:09:33.627
1Oh, I'm well aware. I've updated the question a bit. Thank you :) – rfgamaral – 2019-03-05T23:12:57.743
Shouldn't you at least remove all the spaces? – Adám – 2019-03-05T23:14:56.817
2I don't know JS, but one way to clamp is to sort
[0,n,255]
and take the middle element -- might that be shorter? – xnor – 2019-03-05T23:26:54.7331
@xnor Unfortunately, the JS
– Arnauld – 2019-03-05T23:30:35.203sort()
method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)5@Arnauld Wow, that's pretty silly. But it looks like it would be longer even if the sort was numerical. – xnor – 2019-03-05T23:34:56.153
I can't imagine a case where a length 1 array would be golfier than the approaches suggested, but just out of interest, JavaScript has built in support for clamped 8 bit unsigned ints: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray
– trichoplax – 2019-03-08T18:29:03.863