UNPKG

1.1 kBJavaScriptView Raw
1'use strict'
2/*
3 * Special Cases:
4 * n >> -n = N
5 * n >> N = N
6 * N >> n = N
7 * I >> I = N
8 * n >> 0 = n
9 * I >> n = I
10 * -I >> n = -I
11 * -I >> I = -I
12 * n >> I = I
13 * -n >> I = -1
14 * 0 >> n = 0
15 *
16 * @param {BigNumber} value
17 * @param {BigNumber} value
18 * @return {BigNumber} Result of `x` >> `y`
19 *
20 */
21module.exports = function rightArithShift (x, y) {
22 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
23 throw new Error('Integers expected in function rightArithShift')
24 }
25
26 const BigNumber = x.constructor
27 if (x.isNaN() || y.isNaN() || (y.isNegative() && !y.isZero())) {
28 return new BigNumber(NaN)
29 }
30 if (x.isZero() || y.isZero()) {
31 return x
32 }
33 if (!y.isFinite()) {
34 if (x.isNegative()) {
35 return new BigNumber(-1)
36 }
37 if (!x.isFinite()) {
38 return new BigNumber(NaN)
39 }
40 return new BigNumber(0)
41 }
42
43 // Math.pow(2, y) is fully precise for y < 55, and fast
44 if (y.lt(55)) {
45 return x.div(Math.pow(2, y.toNumber()) + '').floor()
46 }
47 return x.div(new BigNumber(2).pow(y)).floor()
48}