parsix
v5.1.3
Published
A lightweight and customizable JavaScript parser framework that processes strings based on user-defined keywords and actions. Perfect for building flexible, extensible parsing solutions.
Maintainers
Readme
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 parsixUsage
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!EarthClient (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!EarthAPI
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.
- Parameters:
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 theactionsobject. 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 theactionsobject. 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 hasstartIndexas the beginning of the part,endIndexas the end of the part, andcutas 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 theactionsobject. Example:
actions.skip();stop(): Immediately halts the parsing process. The current result is returned. Returns theactionsobject. Example:
actions.stop();process(): (optionalKeywordonly): 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:
- Add a Test Script to
package.json: Add the following line to thescriptssection in yourpackage.json:
"scripts": {
"test": "node test.js"
}- Run the Tests: Use the following command to execute the tests:
npm run test- 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.
