I have the following code I've been developing, an alternate while
loop:
_while = (cond, act) => cond && act() & _while(cond, act)
In this case act()
is intended to alter the end result of cond
with each iteration until cond
is evaluated to false
, to which then the loop is meant to end...
I've tried to test this out by attempting to determine the length of a string through stepping through the string using my code. As a result, my code is the following:
len = 0; _while(!!("qwerty")[len], ()=>++len);
Now, my thoughts were that this code will basically step through and test for the presence of each character within the string, incrementing len
until it attempts "qwe"[6]
which is undefined
, and the !!
renders the undefined
returned value to false
, exiting the loop, with the value of len
being equal to 6
...
However, I'm not even getting that far... for some reason this loop keeps going, and gives up with an error of InternalError: too much recursion
Can anyone see what I've done wrong with my code? I'd like to preserve what I can of my original code without having to resort to a native for
or while
loop...
The expression !!("qwerty")[len])
is evaluated before the call to _while
is actually made. At that time, len
is 0
, so the result of the expression will be true
.
To fix this, you could require cond
to be a function, much like act
is. This way, you can evaluate the condition each time through the loop. I guess it would look like this (though I'm not JavaScript savvy):
_while = (cond, act) => cond() && act() & _while(cond, act)
The given example would then become
len = 0; _while(()=>!!("qwerty")[len], ()=>++len);