UNPKG

918 BJavaScriptView Raw
1'use strict'
2
3/**
4 * Bitwise left shift
5 *
6 * Special Cases:
7 * n << -n = N
8 * n << N = N
9 * N << n = N
10 * n << 0 = n
11 * 0 << n = 0
12 * I << I = N
13 * I << n = I
14 * n << I = I
15 *
16 * @param {BigNumber} x
17 * @param {BigNumber} y
18 * @return {BigNumber} Result of `x` << `y`
19 *
20 */
21module.exports = function leftShift (x, y) {
22 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
23 throw new Error('Integers expected in function leftShift')
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 (!x.isFinite() && !y.isFinite()) {
34 return new BigNumber(NaN)
35 }
36
37 // Math.pow(2, y) is fully precise for y < 55, and fast
38 if (y.lt(55)) {
39 return x.times(Math.pow(2, y.toNumber()) + '')
40 }
41 return x.times(new BigNumber(2).pow(y))
42}