Skip to content

Commit 36ddbe4

Browse files
committed
[js] Fix our asIntN "polyfill"
1 parent a5fc630 commit 36ddbe4

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/vm/js/nqp-runtime/as-int-n.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
const JSBI = require('jsbi');
22

3+
/* as defined in the ECMA-262 spec */
4+
function modulo(bigint, power) {
5+
const mod = JSBI.remainder(bigint, power);
6+
7+
if (JSBI.lessThan(mod, JSBI.BigInt(0))) {
8+
return JSBI.add(mod, power);
9+
} else {
10+
return mod;
11+
}
12+
}
13+
314
module.exports.asIntN = function(bits, bigint) {
415
const power = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(bits));
5-
const mod = JSBI.remainder(bigint, power);
16+
17+
const mod = modulo(bigint, power);
18+
619
return (JSBI.greaterThanOrEqual(mod, JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(bits-1))) ? JSBI.subtract(mod, power) : mod);
720
};
821

922
module.exports.asUintN = function(bits, bigint) {
10-
return JSBI.remainder(bigint, JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(bits)));
23+
return modulo(bigint, JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(bits)));
1124
};
1225

0 commit comments

Comments
 (0)