1.0.0 • Published 2 years ago

@fork-bench/flexjs-open v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

flexjs-open is a home-made Flex utility. It's quite easy to use, and has small presets like DIGITS or LETTERS as well as WORDS and NUMBERS.

Simple example : Polish math notation in JS :

const Flex = require('@fork-bench/flexjs-open');

var pile = [];

var input = '300 2 5 * -'
// In standard notation, it would be 300 - (2 * 5)
// See more on : https://en.wikipedia.org/wiki/Reverse_Polish_notation

// Tokens with their value
var tokens = {
    "-": "operator",
    "+": "operator",
    "*": "operator",
    "/": "operator"
};
// Equivalent in Flex :
//      operator [\-\+\*\/]


// Import everything
const flex = new Flex(input, tokens, NUMBERS = true);

// On each NUMBER 
flex.on('NUMBER', (token) => {
    pile.push(parseInt(token.key));
});

// On each operator
flex.on('operator', (token) => {
    var pileLength = pile.length;
    var result = undefined;
    switch (token.key) {
        case '+':
            result = pile[pileLength - 2] + pile[pileLength - 1];
            break;
        case '-':
            result = pile[pileLength - 2] - pile[pileLength - 1];
            break;
        case '*':
            result = pile[pileLength - 2] * pile[pileLength - 1];
            break;
        case '/':
            result = pile[pileLength - 2] / pile[pileLength - 1];
            break;
    }
    pile.pop();
    pile.pop();
    pile.push(result);

    if (pile.length == 1) {
        console.log(pile[0]);
    }

});

// Run the tokenizer
flex.tokenize();