3.0.1 • Published 4 months ago

parsix v3.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
4 months ago

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 add, 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': (actions) => {actions.add('Hi!'); actions.skip();},
    'world': (actions) => {actions.add('Earth'); actions.skip();},
    '!': Parser.word(''),
};

const defaultKeyword = (actions) => {actions.add(actions.keyword.toUpperCase()); actions.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': (actions) => {actions.add('Hi!'); actions.skip();},
    'world': (actions) => {actions.add('Earth'); actions.skip();},
    '!': Parser.word(''),
};

const defaultKeyword = (actions) => {actions.add(actions.keyword.toUpperCase()); actions.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: An object where keys are strings to match, and values are functions defining actions when the keyword is encountered.
  • defaultKeyword (optional): A function to handle unmatched patterns. Defaults to skipping unrecognized characters.
  • optionalKeyword (optional): A function that is called every time a new keyword is called. By default, it does nothing.

Methods

  • parse(string): Parses the input string based on provided keywords and the default behavior.
    • Parameters:
      • string (string): The input string to parse.
    • Returns: The processed result as a array.

Static Helpers

  • Parser.same(actions): Adds the matched keyword to the result and skips it.
  • Parser.sames(...keywords): Creates an object where each provided keyword shares the same behavior.
  • Parser.word(word): Returns a function to replace a keyword with a specific word.

Actions Object

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

Methods

  • add(content = keyword): Appends content (defaulting to the current keyword) to the result array being constructed. Example:
actions.add('ReplacementText');
  • skip(): Removes the matched keyword from further processing and advances the parsing index. This is essential to avoid reprocessing the same keyword. Example:
actions.skip();
  • stop(): Immediately halts the parsing process. The current result is returned. Example:
actions.stop();

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);
  • 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);

Example

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

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

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.

3.0.1

4 months ago

3.0.0

4 months ago

2.1.1

4 months ago

2.1.0

4 months ago

2.0.0

4 months ago

1.0.1

4 months ago

1.0.0

4 months ago