We've encountered a problem that happens randomly and I try to understand what's going on here. There's no need to understand what the code eventually do. the code is exactly the same except how we try to "truthify" a specific value"
Foo and Bar (fiddle is here) are exactly the same functions.
Differences are here :
(essentially, we're trying to "truethify" the lsbValue)
We've tested it via this code (the same function runs on both Foo and Bar )
function testGalois(fn) {
const x = new Uint32Array([2425393296, 2425393296, 2425393296, 2425393296]);
const y = new Uint32Array([3692772234, 3144594163, 3014792419, 2386452453]);
const expected = [2793996538, 14267392, 3369100906, 2506634262];
for (let i = 0; i < 100; i++) {
const result = Array.from(fn(x, y));
if (JSON.stringify(result) != JSON.stringify(expected)) {
console.error('Failed on iteration', i, 'expected', expected, 'result', result)
return;
}
}
console.log('Pass!');
}
Foo is running flawlessly everytime.
However, Bar fails at a random iteration:
Testing Foo
Pass!
Testing Bar
Failed on iteration 64 expected [ 2793996538, 14267392, 3369100906, 2506634262 ] result [ 4021467969, 3143765947, 1936448977, 785616812 ]
Let's run it again , now the error on different iteration :
Testing Foo
Pass!
Testing Bar
Failed on iteration 62 expected [ 2793996538, 14267392, 3369100906, 2506634262 ] result [ 4021467969, 3143765947, 1936448977, 785616812 ]
Please notice that we're only after the truthy value of
let lsbValue = !!(Vi[3] & 1 ) ; //fails at some iteration.
From my testing in Bar :
const lsbValue = !!(Vi[3] & 1 ) ; //fails
const lsbValue = Boolean(Vi[3] & 1 ) //fails
const lsbValue = (Vi[3] & 1 )>0 //works
But then I thought that maybe there is some kind of shared resource being used here when trying to Boolean or !! which led me to create new Boolean(X) at each iteration rather than Boolean(X):
const lsbValue = new Boolean((Vi[3] & 1 )).valueOf() ; //works !
Question
It smells like a shared initial location is being used when using !! or Boolean. ( although I know that !! is an operator.)
But then , creating a new instance per iteration , did the trick :
const lsbValue = new Boolean((Vi[3] & 1 )).valueOf() ;
Why do they yield different/wrong results?
nb
This doesn't happen in chrome. it happens only in node.