then you can remove all of those from earlier too. It is often a good idea to make sure you only have one return in a function, at the end, and get all context values right at the start and save them all right at the end, then they are much less likely to get forgotten. It may sometimes mean you are unnecessarily saving values but the overheads are trivial, and you will be much less likely to have bugs. Forgetting to write values back to context is very easy to do.
Finally the second if would be better as an else.
And if you want to write some code that you look and think how nice it is then instead of using 0 and 1 for dir use -1 and 1. Then you can add it to count rather than testing to see what you need to do. When the value gets to the min or max you can negate dir.
That counts up to 10 which is what was originally asked for, if you actually want up to 11 which is what the solutions have been doing so far then change the 20s to 22 and the 10 to 11.
Well, I'm using the counter to gradually light up a LED bar composed of 10 LEDs. So, the counter should start at 0 (all LEDs OFF) and count up to 10 (all LEDs ON). The detection of 11 is to reverse the count. Depending of the speed, a moving wave is created with the lighting of the LEDs.
We went from 16 lines of coding to only 4. Outstanding!!
Well,,,sometimes the cost will be loss of readability, @Colin is for sure showing a very compact and brilliant code but it might be difficult to read & understand at first glance. But clever, indeed!!! All my credits
A related question when spending time in making code compact like this, will there be any performance or less memory consumption or other benefits? I mean if you write code in a compiled language, the compiler will anyway optimize your code. But what with javascript in NR? Will node.js optimize anyhow in some way?
I agree, often compact code can be difficult to understand, and my earlier go with the relatively complex arithmetic and comparing to non-obvious numbers like 5.5 falls into that category. The latest one though is not complex, in fact I would argue it is simpler than the the original code with a direction flag and the logic to decide whether to count up or down. It removes a context variable which is a good thing.
The logic is very simple it creates a counter going from 0 to 19 by using modulus 20 and then if the count is <= 10 it returns that, if it is > 10 it returns 20 - the count, so as count goes up 11 to 19 the returned value goes down again from 9 to 1.
In terms of run time efficiency I suspect the last one might just beat the others, but I imagine the difference will be very small.