parsix

5.1.3 • Public • Published

parsix

parsix is a flexible and customizable JavaScript parser framework designed to process strings based on defined keywords and associated actions. It provides a simple API to configure parsing behavior for any input string and allows you to define default behaviors for unrecognized patterns.

Features

  • Customizable Keywords: Define specific actions for keywords during parsing.
  • Default Action: Handle unrecognized patterns with a default behavior.
  • Action Utilities: Built-in actions to set, skip, or stop parsing.
  • Static Helpers: Simplify handling of repetitive parsing logic.
  • Lightweight and Extensible: Easy to integrate into your project.

Installation

Install parsix via npm:

npm install parsix

Usage

You can use parsix both on the server side with Node.js and on the client side by importing it directly.

Server (Node.js)

Here's an example of using parsix on the server:

import Parser from 'parsix';

const keywords = {
    'hello': 'Hi!', // Example using string
    'world': (actions) => {actions.set('Earth').skip();}, // Example using the function
    '!': ''
};

const defaultKeyword = (actions) => {actions.set(actions.keyword.toUpperCase()).skip();}

const parser = new Parser(keywords, defaultKeyword);

const input = 'hello world!';
const result = parser.parse(input).join('');

console.log(result); // Output: Hi!Earth

Client (Browser)

To use parsix on the client side, import it directly from the node_modules directory:

import Parser from './path/to/node_modules/parsix/index.js';

const keywords = {
    'hello': 'Hi!', // Example using string
    'world': (actions) => {actions.set('Earth').skip();}, // Example using the function
    '!': ''
};

const defaultKeyword = (actions) => {actions.set(actions.keyword.toUpperCase()).skip();}

const parser = new Parser(keywords, defaultKeyword);

const input = 'hello world!';
const result = parser.parse(input).join('');

console.log(result); // Output: Hi!Earth

API

Parser

Constructor

new Parser(keywords, defaultKeyword, optionalKeyword)
  • keywords (optional): An object in which the keys are the strings to match and the values ​​are functions that specify what to do when a keyword or string is encountered that should replace the keywords. By default it is an empty object.
  • defaultKeyword (optional): Function to handle unmatched patterns or a string to replace them. Defaults to skipping unrecognized characters.
  • optionalKeyword (optional): A function that is called every time and never when the keyword is called. Defaults to calling the keyword's handler process.

Methods

  • parse(string): Parses the input string based on provided keywords and the default behavior.
    • Parameters:
      • string (string, optional): The input string to parse. Default is an empty string.
    • Returns: The processed result is an array of processed keywords.

Static Helpers

  • Parser.same(): Returns a function that returns the matched keyword.
  • Parser.sames(...keywords): Creates an object where each provided keyword shares the same behavior.

Actions Object

The actions object is passed to each keyword handler. It provides methods and properties to control the parsing process.

Methods

  • set(content = keyword, index = actions.result.length): Inserts content (default is the current keyword), which can be either an array (will insert multiple elements) or a string, into the created result array at the index location (default is at the end). Returns the actions object. Example:
actions.set('ReplacementText', actions.result.length);
  • unset(index = actions.result.length - 1, length = 1): Removes content starting at index (default is end) with the specified content length. Returns the actions object. Example:
actions.unset(actions.result.length - 1, 1);
  • select(criteria): Returns information about the found part of the results by the criterion (can be either a function that returns the condition for the currently found part, or a string that denotes the keyword with which the part should begin), passes as an argument an object that has startIndex as the beginning of the part, endIndex as the end of the part, and cut as the found part. Example:
console.log(actions.select('{'));
  • skip(): Removes the matched keyword from further processing and advances the parsing index. This is essential to avoid reprocessing the same keyword. Returns the actions object. Example:
actions.skip();
  • stop(): Immediately halts the parsing process. The current result is returned. Returns the actions object. Example:
actions.stop();
  • process(): (optionalKeyword only): Causes the appropriate processing of the found keyword.
actions.process();

Properties

  • relativeIndex: The current index of the parser relative to the substring being processed. Example:
console.log(actions.relativeIndex);
  • absoluteIndex: The absolute index of the parser in the entire input string. Example:
console.log(actions.absoluteIndex);
  • current: The remaining unprocessed portion of the input string. Example:
console.log(actions.current); // Shows the substring starting from `relativeIndex`.
  • result: The array that has been constructed so far. Example:
console.log(actions.result);
  • usedKeywords: An array of keywords processed so far. Example:
console.log(actions.usedKeywords);
  • keyword: The currently matched keyword being processed. Example:
console.log(actions.keyword);
  • source: The string with which the parsing process takes place. Example:
console.log(actions.source);
  • thisParser: An instance of this parser. Example:
console.log(actions.thisParser);

Example

Here's how you can use parsix to build a JSON parser:

const jsonParser = new Parser({
    '{': Parser.same(),
    '}': Parser.same(),
    '"': (actions) => {
        const endIndex = actions.current.indexOf('"', actions.relativeIndex + 1);
        if (endIndex !== -1) {
            const value = actions.current.slice(actions.relativeIndex + 1, endIndex);
            actions.set(`"${value}"`);
            actions.relativeIndex = endIndex; // Move index to closing quote
            actions.skip();
        } else {
            actions.stop(); // Stop if no matching quote is found
        }
    }
}, (actions) => {
    actions.set(actions.keyword).skip(); // Default: append unmatched characters
});

const jsonString = '{"name": "John", "age": 30}';
const parsed = jsonParser.parse(jsonString).join('');

console.log(parsed); // Output: {"name": "John", "age": 30}

Running Tests

To run the tests for parsix, follow these steps:

  1. Add a Test Script to package.json: Add the following line to the scripts section in your package.json:
"scripts": {
    "test": "node test.js"
}
  1. Run the Tests: Use the following command to execute the tests:
npm run test
  1. Check the Results: The test output will appear in the console, indicating whether each test has passed or failed.

License

parsix is licensed under the MIT License.

Package Sidebar

Install

npm i parsix

Weekly Downloads

5

Version

5.1.3

License

MIT

Unpacked Size

18.4 kB

Total Files

4

Last publish

Collaborators

  • drakalyebus