(Fixed formatting due to code being parsed as wiki formatting.) Tags: Visual edit apiedit |
(Oops, was wrong about a minimal clamp function. Edited to make it more minimal.) Tags: Visual edit apiedit |
||
Line 1: | Line 1: | ||
==Keeping a value between two other values== |
==Keeping a value between two other values== |
||
− | Clamp is a classic function to keep a number (a) between two values (b and c). There are multiple ways to write this function, but the following two methods use minimal tokens and characters. Which you use depends on how clear or concise you want your code. |
+ | Clamp is a classic function to keep a number (a) between two values (b and c). There are multiple ways to write this function, but the following two methods try to use minimal tokens and characters. Which you use depends on how clear or concise you want your code. |
− | This |
+ | This function uses only 15 tokens and 50 characters. |
<pre>function clamp(a,b,c) |
<pre>function clamp(a,b,c) |
||
− | return |
+ | return min(c,max(a,b)) |
end</pre> |
end</pre> |
||
⚫ | |||
− | |||
− | |||
− | |||
⚫ | |||
<pre>function clamp(a,b,c) |
<pre>function clamp(a,b,c) |
||
if (a<b) return b |
if (a<b) return b |
Revision as of 21:46, 17 June 2017
Keeping a value between two other values
Clamp is a classic function to keep a number (a) between two values (b and c). There are multiple ways to write this function, but the following two methods try to use minimal tokens and characters. Which you use depends on how clear or concise you want your code.
This function uses only 15 tokens and 50 characters.
function clamp(a,b,c) return min(c,max(a,b)) end
This function is more readable, but it uses 22 tokens and 73 characters.
function clamp(a,b,c) if (a<b) return b if (a>c) return c return a end