The following would log -1 in console, instead of 6:
function indexOf(a, suba, aStart, aEnd, subaStart, subaEnd, eq) {
var j = subaStart,
k = -1;
var subaLen = subaEnd - subaStart + 1;
while (aStart <= aEnd && aEnd - aStart + 1 >= subaLen) {
if (eq(a[aStart], suba[j])) {
if (k < 0) k = aStart;
j++;
if (j > subaEnd) return k;
} else {
k = -1;
j = subaStart;
}
aStart++;
}
return -1;
}
var slong = 'happy cat in the black';
var sshort = 'cat in the';
indexOf(
slong,
sshort,
0,
slong.length - 1,
0,
sshort.length - 1,
(a, b) => a === b
);
However, with slong = 'cat in the' and sshort = 'in' the result is 4.
The reason is that the char by char parse stops when a match is found but, while keep looping, aEnd - aStart + 1 >= subaLen becomes false so that last part of the string is never checked if the right boundary is not as long as the searched string itself.
Is this meant to behave this way? If that's the case, wouldn't be wiser to call the function halfIndexOf ?
The following would log
-1
in console, instead of6
:However, with
slong = 'cat in the'
andsshort = 'in'
the result is4
.The reason is that the char by char parse stops when a match is found but, while keep looping,
aEnd - aStart + 1 >= subaLen
becomes false so that last part of the string is never checked if the right boundary is not as long as the searched string itself.Is this meant to behave this way? If that's the case, wouldn't be wiser to call the function
halfIndexOf
?Thanks for any sort of clarification