Only problem with this is mutualFollowers
is not defined in the above code sample. We are left to assume,
let mutualFollowers = [];
appears somewhere above this sample in the complete code. That stipulated, we could rationalize that at this point there is no .push()
method on Array
class objects.
Algorithm wise it is sound, though. To emulate .push
your code need only return the length of the mutualFollowers array.
return mutualFollowers.length;
but since the sample is not a function, that is not doable.
let m = mutualFollowers; // create symbol from long name
let b = bobsFollowers;
let t = tinasFollowers;
If there is ever any question what b , m, and t are, we need only look up in the source code for definition. Long names are useful in the big picture, but in the mechanics they serve little use.
let i = 0; j;
for (i; i < b.length; i++) {
let x = b[i];
for (j = 0; j < t.length; j++) {
x === t[j] ? m.push(x) : null;
}
}
Sneaky how a ternary expression can lessen the burden from time to time. This one does something on true, and nothing on false. One expression, and no if statement.
The console will respond with null
if the last comparison is false, and with the length of mutualFollowers
array if the it is true. This goes right back to what Chris said in the OP. .push()
returns the array size.
Convince me that the above symbol approach is not easier to read with the same purpose in mind.
Were we to write it without .push()
,
let k = 0;
...
m[k++] = x
Your algorithm refactors beautifully. With no push
. But there is a shove. We still need to apply the condition.
m[k++] = x === t[j] ? x : null;
m
is rather unruly, though,
["john", null, null, null, null, null, null, null, null, null, null, "sam"]
A quick fix with an iterator,
console.log(m.filter(x => x && true)) // null undefined 0 NaN "", all fail
["john", "sam"]
but then, if we don’t have push, we don’t have filter, either. Seems we’re working backward, but it is a worthwhile exercise.
Say we do have filter…
console.log(m.filter(x => !! x))
["john", "sam"]