I was doing a question on codility and came across this problem for which I wrote something like this:
function impact(s) {
let imp = 4; // max possible impact
for (let i = 0; i < s.length; i++) {
if (s[i] === 'A') return 1;
else if (s[i] === 'C') imp = Math.min(imp, 2);
else if (s[i] === 'G') imp = Math.min(imp, 3);
else if (s[i] === 'T') imp = Math.min(imp, 4);
}
return imp;
}
function solution(S, P, Q) {
const A = new Array(P.length);
for (let i = 0; i < P.length; i++) {
const s = S.slice(P[i], Q[i] + 1);
A[i] = impact(s);
}
return A;
}
And it failed all the performance tests
Now I changed it to the following code which I thought would be slower but to my surprise it scored 100%:
function solution(S, P, Q) {
let A = []
for (let i = 0; i < P.length; i++) {
let s = S.slice(P[i], Q[i] + 1)
if (s.indexOf('A') > -1) A.push(1)
else if (s.indexOf('C') > -1) A.push(2)
else if (s.indexOf('G') > -1) A.push(3)
else if (s.indexOf('T') > -1) A.push(4)
}
return A
}
Which to me made no sense, because I was using 4 indexOf which should be slower than 1 linear iteration of the same string. But it's not.
So, how does String.indexOf() work and why are 4 .indexOf so much faster than 1 iteration?