Brendan Eich wrote:
Andreas Rossberg wrote:
Hm, I don't see how this example relies on an in-band sentinel. The
loop condition would work just as well with a comparison to undefined.
Everything else is regular argument values.
This loop could indeed test
while ((i = s.indexOf(' ', j)) !== undefined) ...
That is unsightly, overlong, and contrived, but never mind.
What I was trying to get to -- and utterly failed to get to last time
-- was a use of the -1 return value. Here's what I should have
written, a "split on single-char string" that does not rely on
trailing separator (i.e. termination):
var s = "a bbb cccc ddddd"
var i, j = 0;
var a = [];
do {
i = s.indexOf(' ', j);
a.push(s.slice(j, i));// j lags i and slice(j, -1) returns tail
} while ((j = i + 1) != 0);
print(a);
This prints
a,bbb,cccc,dddd
Sorry, missed my off by one at the end (morning coffee not strong enough!).
Try this:
var s = "a bbb cccc ddddd\n"
var i, j = 0;
var a = [];
do {
i = s.indexOf(' ', j);
print(j, i);
} while ((j = i + 1) != 0);
print(a + '!');
The trailing \n in s is supposed to be skipped, so this prints
a,bbb,cccc,ddddd
I will take the charge of "contrived" but still maintain that -1 rather
than undefined can be useful (as in used in a further index
computation), while undefined either needs a test to special-case (and
avoid hard-to-see implicit conversion), or else a conversion to NaN that
happens to work (a "good" implicit conversion? Not in your book, I'm sure!).
/be
Here, using undefined instead of -1 does not work -- you get an iloop
becanse NaN != 0.
Contrived? Less so than a forced undefined sentinel. This is a
simplified split that handles the no-separator basis case correctly.
Similar examples come up from time to time in the real world.
Multiply typed return values for indexOf, charAt and probably others,
depending on the particulars, can be losing not winning. I'm not going
to generalize, but I am here to argue against a generalization that I
thought I read, where OOB return is always "failure" and must be
signified by a differently-typed sentinel.
I don't believe that leads to the most usable API in general, and it
also can run afoul of implicit conversions.
/be
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss