bylexus / fparse

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

Added support for string parameters and variables #56

Closed LuigiPulcini closed 5 months ago

LuigiPulcini commented 5 months ago

If there is any interest in adding support for string parameters and variables, this PR adjusts the version forked by @issidorov (https://github.com/issidorov/fparse/), updating it to the latest master branch (including the refactoring to Typescript).

This is also requested in #51.

An example of what this version can do is offered below:

const f1 = new Formula( 'if( compare( [quantity], 10, ">=" ), .9, 1 ) * [price]' );

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

f1.compare = ( value, reference, comparison ) => {
    switch ( comparison ) {
        case '>=':
            return value >= reference ? 1 : 0;
        ...
        case '>':
        default:
            return value > reference ? 1 : 0;
    }
};

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

// res = 900

I hope this helps.

LuigiPulcini commented 5 months ago

Hi, @bylexus.

First of all, thank you so much for promptly reviewing my pull request. I am sorry I completely missed the fact that the tests would all fail with the library refactoring in Typescript.

I have now adjusted a few more details in the library and fixed all the tests accordingly. When I run npm run test, everything runs smoothly, now.

bylexus commented 5 months ago

Hi @LuigiPulcini,

Thanks for your contribution, this is a valuable addition. I did some adaptions to your original pull request, mostly type definitions and some documentation.

For the time being, I merged it back to the develop branch, I want to implement some additional changes before merging it to the main and creating a version, namely:

As soon as I added those additions, I will publish a new version.