Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is it possible to overload arithmetic operators to support own bigint objects? #198

Closed
mgttt opened this issue Jul 14, 2019 · 1 comment
Closed
Labels

Comments

@mgttt
Copy link

mgttt commented Jul 14, 2019

dear, is it possible to overload the operators to support own bigint? e. g.
parse("a**b%c", {a:new BN("123456789"),b:new BN("654321"),c:new BN("76584")})

@silentmatt
Copy link
Owner

silentmatt commented Jul 16, 2019

Yes, you can although you'll need to be careful how you handle numeric literals in the expression, since those will be parsed as native JavaScript numbers. The Parser class has a couple properties that provide the implementation for the various built-in operators and functions. You can replace those with your own implementation, or add/remove functions. Here's a quick made-up example that should give you an idea. You can look at the Parser constructor for the full list of operators and functions.

var parser = new Parser();

// Note that the exponentiation operator is ^, not **
parser.binaryOps['^'] = function (a, b) {
    // Convert JavaScript numbers to big integers
    if (!BN.isBN(a)) {
        a = new BN(a);
    }
    if (!BN.isBN(b)) {
        b = new BN(b);
    }
    return a.pow(b);
};

parser.binaryOps['%'] = function (a, b) {
    if (!BN.isBN(a)) {
        a = new BN(a);
    }
    if (!BN.isBN(b)) {
        b = new BN(b);
    }
    return a.mod(b);
};

// etc. for unaryOps, binaryOps, ternaryOps, functions, and/or consts

var answer = parser.parse("a^b%c", {a:new BN("123456789"),b:new BN("654321"),c:new BN("76584")}).evaluate()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants