bylexus / fparse

A JavaScript Formula Parser
http://fparser.alexi.ch/
MIT License
89 stars 15 forks source link

Add logical operators and expressions #57

Closed LuigiPulcini closed 1 month ago

LuigiPulcini commented 1 month ago

This PR adds the possibility of having logical operators and expressions in a formula.

Possible operators are >, <, >=, <=, = and !=, the meaning of which is trivial.

Since the final goal is to use those operators in a mathematical formula, the result of a logical expression will always return a number: either 1 (when the expression is true) or 0 (when it is false), which can easily be used in a formula to achieve conditional calculations.

An example of a logical expression used in a formula is:

const f1 = new Formula( '[price] * ( 1 + 0.25 * ( [weight] > 10 )' );

const res = f1.evaluate( { price: 100, weight: 12.4 } );
console.log( res );

// res = 125

This would be essential to implement some logical functions – such as IF() – in the same form Microsoft Excel or Google Sheets do:

const f1 = new Formula( 'IF( [weight] > 10, 1.25, 1 ) * [price]' );

f1.IF = ( value, ifTrue, ifFalse ) => {
    return value ? ifTrue : ifFalse;
};

const res = f1.evaluate( { price: 100, weight: 12.4 } );
console.log( res );

// res = 125
bylexus commented 1 month ago

This is a useful addition, as it opens the possibility to implement conditional logic, thanks.

Would you mind:

Then I will consider your addition to be merged.

Many thanks for your contribution.

LuigiPulcini commented 1 month ago

Hi, @bylexus,

Thanks for reviewing my PR so swiftly. I followed both of your recommendations. While adding Unit tests, I spotted a few missing declarations for the new Logical Expression, which I added now, and rebuilt all the distribution files.

Let me know if the tests are enough and if there is anything else I can do.

bylexus commented 1 month ago

OK, I have decided that your solution and your implementation of the operator precedence is correct. I will merge your contribution into my develop branch, add some documentation and examples, and release a new version.

many thanks for your useful contribution.

LuigiPulcini commented 1 month ago

Thanks for reviewing the PR so thoroughly. I am glad that, in the end, it worked out as intended!