aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/maybe_big_number.ts
blob: 95fbd86952c893ecfd4775b29903a4cce4318b44 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { BigNumber } from '@0x/utils';
import * as _ from 'lodash';

import { Maybe } from '../types';

export const maybeBigNumberUtil = {
    // converts a string to a Maybe<BigNumber>
    // if string is a NaN, considered undefined
    stringToMaybeBigNumber: (stringValue: string): Maybe<BigNumber> => {
        let validBigNumber: BigNumber;
        try {
            validBigNumber = new BigNumber(stringValue);
        } catch {
            return undefined;
        }

        return validBigNumber.isNaN() ? undefined : validBigNumber;
    },
    areMaybeBigNumbersEqual: (val1: Maybe<BigNumber>, val2: Maybe<BigNumber>): boolean => {
        if (!_.isUndefined(val1) && !_.isUndefined(val2)) {
            return val1.isEqualTo(val2);
        }
        return _.isUndefined(val1) && _.isUndefined(val2);
    },
    // converts a BigNumber or String to the BigNumber used by 0x libraries
    toMaybeBigNumber: (value: any): Maybe<BigNumber> => {
        if (_.isString(value)) {
            return maybeBigNumberUtil.stringToMaybeBigNumber(value);
        }
        // checks for pre v8 bignumber with member variable
        if (BigNumber.isBigNumber(value) || value.isBigNumber) {
            return new BigNumber(value.toString());
        }
        return undefined;
    },
};