UNPKG

1.4 kBJavaScriptView Raw
1'use strict'
2const bitwise = require('./bitwise')
3
4/**
5 * Bitwise and for Bignumbers
6 *
7 * Special Cases:
8 * N & n = N
9 * n & 0 = 0
10 * n & -1 = n
11 * n & n = n
12 * I & I = I
13 * -I & -I = -I
14 * I & -I = 0
15 * I & n = n
16 * I & -n = I
17 * -I & n = 0
18 * -I & -n = -I
19 *
20 * @param {BigNumber} x
21 * @param {BigNumber} y
22 * @return {BigNumber} Result of `x` & `y`, is fully precise
23 * @private
24 */
25module.exports = function bitAnd (x, y) {
26 if ((x.isFinite() && !x.isInteger()) || (y.isFinite() && !y.isInteger())) {
27 throw new Error('Integers expected in function bitAnd')
28 }
29
30 const BigNumber = x.constructor
31 if (x.isNaN() || y.isNaN()) {
32 return new BigNumber(NaN)
33 }
34
35 if (x.isZero() || y.eq(-1) || x.eq(y)) {
36 return x
37 }
38 if (y.isZero() || x.eq(-1)) {
39 return y
40 }
41
42 if (!x.isFinite() || !y.isFinite()) {
43 if (!x.isFinite() && !y.isFinite()) {
44 if (x.isNegative() === y.isNegative()) {
45 return x
46 }
47 return new BigNumber(0)
48 }
49 if (!x.isFinite()) {
50 if (y.isNegative()) {
51 return x
52 }
53 if (x.isNegative()) {
54 return new BigNumber(0)
55 }
56 return y
57 }
58 if (!y.isFinite()) {
59 if (x.isNegative()) {
60 return y
61 }
62 if (y.isNegative()) {
63 return new BigNumber(0)
64 }
65 return x
66 }
67 }
68 return bitwise(x, y, function (a, b) { return a & b })
69}