Is it possible to make a clamp function shorter than a ternary in JS?Let's create random number...

I can't die. Who am I?

A bug in Excel? Conditional formatting for marking duplicates also highlights unique value

How to lift/raise/repair a segment of concrete slab?

What is a term for a function that when called repeatedly, has the same effect as calling once?

Giving a talk in my old university, how prominently should I tell students my salary?

Dystopian novel where telepathic humans live under a dome

Graphing random points on the XY-plane

Misplaced tyre lever - alternatives?

It took me a lot of time to make this, pls like. (YouTube Comments #1)

How can I be pwned if I'm not registered on the compromised site?

Second-rate spelling

Why doesn't Object.keys return a keyof type in TypeScript?

What is this waxed root vegetable?

VAT refund for a conference ticket in Sweden

Achieving MPPT of a solar panel with LM2596

How to evaluate the limit where something is raised to a power of x?

Citing contemporaneous (interlaced?) preprints

Are there any other Chaos-worshipping races?

Is there a math equivalent to the conditional ternary operator?

How can atoms be electrically neutral when there is a difference in the positions of the charges?

How can I handle a player who pre-plans arguments about my rulings on RAW?

Adding days to the Date portion of DateTime throws off the Time portion

Analog Mute Circuit - Simplest Solution

Rationale to prefer local variables over instance variables?



Is it possible to make a clamp function shorter than a ternary in JS?


Let's create random number genratorBase-2 integer logarithm of 64-bit unsigned integerInteger square root of integerTweetable Mathematical ArtShortest Minmod FunctionNon-repeating random numbersCompute the Mertens functionMagic popcount numbersBe as evil as possibleTernary Triangles













3












$begingroup$


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.










share|improve this question









New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$












  • $begingroup$
    Hi 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.
    $endgroup$
    – FryAmTheEggman
    1 hour ago










  • $begingroup$
    Oh, I'm well aware. I've updated the question a bit. Thank you :)
    $endgroup$
    – Ricardo Amaral
    1 hour ago










  • $begingroup$
    Shouldn't you at least remove all the spaces?
    $endgroup$
    – Adám
    1 hour ago






  • 1




    $begingroup$
    I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?
    $endgroup$
    – xnor
    1 hour ago






  • 1




    $begingroup$
    @xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)
    $endgroup$
    – Arnauld
    1 hour ago
















3












$begingroup$


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.










share|improve this question









New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$












  • $begingroup$
    Hi 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.
    $endgroup$
    – FryAmTheEggman
    1 hour ago










  • $begingroup$
    Oh, I'm well aware. I've updated the question a bit. Thank you :)
    $endgroup$
    – Ricardo Amaral
    1 hour ago










  • $begingroup$
    Shouldn't you at least remove all the spaces?
    $endgroup$
    – Adám
    1 hour ago






  • 1




    $begingroup$
    I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?
    $endgroup$
    – xnor
    1 hour ago






  • 1




    $begingroup$
    @xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)
    $endgroup$
    – Arnauld
    1 hour ago














3












3








3





$begingroup$


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.










share|improve this question









New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




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.







code-golf math tips javascript






share|improve this question









New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago







Ricardo Amaral













New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 1 hour ago









Ricardo AmaralRicardo Amaral

1162




1162




New contributor




Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Ricardo Amaral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • $begingroup$
    Hi 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.
    $endgroup$
    – FryAmTheEggman
    1 hour ago










  • $begingroup$
    Oh, I'm well aware. I've updated the question a bit. Thank you :)
    $endgroup$
    – Ricardo Amaral
    1 hour ago










  • $begingroup$
    Shouldn't you at least remove all the spaces?
    $endgroup$
    – Adám
    1 hour ago






  • 1




    $begingroup$
    I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?
    $endgroup$
    – xnor
    1 hour ago






  • 1




    $begingroup$
    @xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)
    $endgroup$
    – Arnauld
    1 hour ago


















  • $begingroup$
    Hi 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.
    $endgroup$
    – FryAmTheEggman
    1 hour ago










  • $begingroup$
    Oh, I'm well aware. I've updated the question a bit. Thank you :)
    $endgroup$
    – Ricardo Amaral
    1 hour ago










  • $begingroup$
    Shouldn't you at least remove all the spaces?
    $endgroup$
    – Adám
    1 hour ago






  • 1




    $begingroup$
    I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?
    $endgroup$
    – xnor
    1 hour ago






  • 1




    $begingroup$
    @xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)
    $endgroup$
    – Arnauld
    1 hour ago
















$begingroup$
Hi 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.
$endgroup$
– FryAmTheEggman
1 hour ago




$begingroup$
Hi 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.
$endgroup$
– FryAmTheEggman
1 hour ago












$begingroup$
Oh, I'm well aware. I've updated the question a bit. Thank you :)
$endgroup$
– Ricardo Amaral
1 hour ago




$begingroup$
Oh, I'm well aware. I've updated the question a bit. Thank you :)
$endgroup$
– Ricardo Amaral
1 hour ago












$begingroup$
Shouldn't you at least remove all the spaces?
$endgroup$
– Adám
1 hour ago




$begingroup$
Shouldn't you at least remove all the spaces?
$endgroup$
– Adám
1 hour ago




1




1




$begingroup$
I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?
$endgroup$
– xnor
1 hour ago




$begingroup$
I don't know JS, but one way to clamp is to sort [0,n,255] and take the middle element -- might that be shorter?
$endgroup$
– xnor
1 hour ago




1




1




$begingroup$
@xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)
$endgroup$
– Arnauld
1 hour ago




$begingroup$
@xnor Unfortunately, the JS sort() method uses a lexicographical comparison by default, so that would require an explicit callback. (Something like that.)
$endgroup$
– Arnauld
1 hour ago










1 Answer
1






active

oldest

votes


















4












$begingroup$

19 bytes



You can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether $n$ is greater than $255$. Because of the bitwise operation, this will however fail for $nge 2^{32}$.





n=>n<0?0:n>>8?255:n


Try it online!





19 bytes



This one returns $false$ instead of $0$ but works for $nge 2^{32}$.





n=>n>255?255:n>0&&n


Try it online!





The original version without whitespace (and without naming the function) is 20 bytes:



n=>n>0?n<255?n:255:0


Try it online!






share|improve this answer











$endgroup$













  • $begingroup$
    Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
    $endgroup$
    – Value Ink
    1 hour ago










  • $begingroup$
    @ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
    $endgroup$
    – Arnauld
    1 hour ago










  • $begingroup$
    @ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
    $endgroup$
    – Arnauld
    48 mins ago











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "200"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Ricardo Amaral is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f180949%2fis-it-possible-to-make-a-clamp-function-shorter-than-a-ternary-in-js%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









4












$begingroup$

19 bytes



You can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether $n$ is greater than $255$. Because of the bitwise operation, this will however fail for $nge 2^{32}$.





n=>n<0?0:n>>8?255:n


Try it online!





19 bytes



This one returns $false$ instead of $0$ but works for $nge 2^{32}$.





n=>n>255?255:n>0&&n


Try it online!





The original version without whitespace (and without naming the function) is 20 bytes:



n=>n>0?n<255?n:255:0


Try it online!






share|improve this answer











$endgroup$













  • $begingroup$
    Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
    $endgroup$
    – Value Ink
    1 hour ago










  • $begingroup$
    @ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
    $endgroup$
    – Arnauld
    1 hour ago










  • $begingroup$
    @ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
    $endgroup$
    – Arnauld
    48 mins ago
















4












$begingroup$

19 bytes



You can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether $n$ is greater than $255$. Because of the bitwise operation, this will however fail for $nge 2^{32}$.





n=>n<0?0:n>>8?255:n


Try it online!





19 bytes



This one returns $false$ instead of $0$ but works for $nge 2^{32}$.





n=>n>255?255:n>0&&n


Try it online!





The original version without whitespace (and without naming the function) is 20 bytes:



n=>n>0?n<255?n:255:0


Try it online!






share|improve this answer











$endgroup$













  • $begingroup$
    Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
    $endgroup$
    – Value Ink
    1 hour ago










  • $begingroup$
    @ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
    $endgroup$
    – Arnauld
    1 hour ago










  • $begingroup$
    @ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
    $endgroup$
    – Arnauld
    48 mins ago














4












4








4





$begingroup$

19 bytes



You can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether $n$ is greater than $255$. Because of the bitwise operation, this will however fail for $nge 2^{32}$.





n=>n<0?0:n>>8?255:n


Try it online!





19 bytes



This one returns $false$ instead of $0$ but works for $nge 2^{32}$.





n=>n>255?255:n>0&&n


Try it online!





The original version without whitespace (and without naming the function) is 20 bytes:



n=>n>0?n<255?n:255:0


Try it online!






share|improve this answer











$endgroup$



19 bytes



You can save a byte by inverting the logic of the ternary tests and using n>>8 to test whether $n$ is greater than $255$. Because of the bitwise operation, this will however fail for $nge 2^{32}$.





n=>n<0?0:n>>8?255:n


Try it online!





19 bytes



This one returns $false$ instead of $0$ but works for $nge 2^{32}$.





n=>n>255?255:n>0&&n


Try it online!





The original version without whitespace (and without naming the function) is 20 bytes:



n=>n>0?n<255?n:255:0


Try it online!







share|improve this answer














share|improve this answer



share|improve this answer








edited 49 mins ago

























answered 1 hour ago









ArnauldArnauld

77.7k694325




77.7k694325












  • $begingroup$
    Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
    $endgroup$
    – Value Ink
    1 hour ago










  • $begingroup$
    @ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
    $endgroup$
    – Arnauld
    1 hour ago










  • $begingroup$
    @ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
    $endgroup$
    – Arnauld
    48 mins ago


















  • $begingroup$
    Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
    $endgroup$
    – Value Ink
    1 hour ago










  • $begingroup$
    @ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
    $endgroup$
    – Arnauld
    1 hour ago










  • $begingroup$
    @ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
    $endgroup$
    – Arnauld
    48 mins ago
















$begingroup$
Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
$endgroup$
– Value Ink
1 hour ago




$begingroup$
Why stop there? If you're extremely liberal with what counts as a 0 (as JavaScript tends to do) you can always go for n=>n>>8?255:n>0&&n for 18 bytes, since false can be coerced to 0 and this will make all negative numbers evaluate to false
$endgroup$
– Value Ink
1 hour ago












$begingroup$
@ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
$endgroup$
– Arnauld
1 hour ago




$begingroup$
@ValueInk If you don't test $n<0$ beforhand, n>>8 will be truthy for any negative input.
$endgroup$
– Arnauld
1 hour ago












$begingroup$
@ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
$endgroup$
– Arnauld
48 mins ago




$begingroup$
@ValueInk I've however added another 19-byte version if supporting integers beyond 32-bit is required.
$endgroup$
– Arnauld
48 mins ago










Ricardo Amaral is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Ricardo Amaral is a new contributor. Be nice, and check out our Code of Conduct.













Ricardo Amaral is a new contributor. Be nice, and check out our Code of Conduct.












Ricardo Amaral is a new contributor. Be nice, and check out our Code of Conduct.
















If this is an answer to a challenge…




  • …Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.


  • …Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
    Explanations of your answer make it more interesting to read and are very much encouraged.


  • …Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.



More generally…




  • …Please make sure to answer the question and provide sufficient detail.


  • …Avoid asking for help, clarification or responding to other answers (use comments instead).





draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f180949%2fis-it-possible-to-make-a-clamp-function-shorter-than-a-ternary-in-js%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Gersau Kjelder | Navigasjonsmeny46°59′0″N 8°31′0″E46°59′0″N...

Hestehale Innhaldsliste Hestehale på kvinner | Hestehale på menn | Galleri | Sjå òg |...

What is the “three and three hundred thousand syndrome”?Who wrote the book Arena?What five creatures were...