UNPKG

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