0.1.6 β€’ Published 12 months ago

@jaielzeus/stringinterpolator v0.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

Contributors Forks Stargazers Issues MIT License

πŸ”Ž About The Project

This project aims to provide developers with a simple tool for interpolating text via variables and (text-processing) functions in their Node.js projects. The need for such a feature naturally arises when dealing with (user-provided) texts that need to be interpolated with data.

-> Check out πŸ› οΈ Usage for the key concepts and πŸ“– Examples for some cool examples!

Features:

  • Blazingly fast! πŸ”₯
  • Recursive interpolation ♾️
  • Unlimited power πŸ’―

πŸš€ Getting Started

To get started simply fulfill the prerequistes, install the package via npm and use it in your code.

⚠️ Prerequisites

If not present on your development environment simply download the latest Node.js + npm version here.

Minimum versions required:

$ npm -v
6.1.12
$ node -v
v12.13.0

πŸ’Ύ Installation

Install the package via npm with he following command:

$ npm i @jaielzeus/stringinterpolator

πŸ› οΈ Usage

Here are the key concepts of how to use the StringInterpolator in your code.

Instantiation

Simply require the package and instantiate an object:

const StringInterpolator = require('@jaielzeus/stringinterpolator');

const interpolator = new StringInterpolator();

Variables

Add a variable and a callback function by calling the addVariable(name, callback) method. The callback will be called with the provided data object when the token for the variable is replaced in the text. A callback function has to provide either a boolean, a number or a string.

interpolator.addVariable('name', (d) => d.name);

Functions

Add a function and a callback function by calling the addFunction(name, callback, self) method. The callback will be called with the provided data object and the content inbetween the delimiters when the token for the function is replaced in the text. A callback function has to provide either a boolean, a number or a string.

interpolator.addFunction('max', (d, c) => Math.max(...c.split(',')));

Interpolator functions take an additional parameter self, which gives them the possibility to process the content between their delimiters by themselves. This is useful for more complex functions which want to process the raw content with their own Stringinterpolator instances using their own variables and functions or with other text processing methods.

function customFunction(d, c){
  StringInterpolator custom = new StringInterpolator();

  custom.addVariable('custom', 'This is a special custom variable only valid inside of the $list() function');

  return custom.process(c, {});
}

interpolator.addFunction('special', customFunction, true);

The returned value of a self processing function will be interpolated normally, just not the content which is given to the function as it would usually be the case.

Providing literals as callbacks

Interpolation variables or functions can also take literals as callbacks (Although not so useful for functions). The literals can be a boolean, a number or a string.

interpolator.addVariable('name', 'JaielZeus');
interpolator.addFunction('year', 2023);

Marker and Delimiters

Interpolation variables and functions have a pre-defined marker (default: '$') in front of them for identification.

"This is a $variable this is a $function()"

Additionally functions have a content that is surrounded by the delimiters(default: '()').

"This is a $function(with content inside)"

A function's registered callback will be called like a variable with the provided data object but also with the content that is inside of the delimiters.

If you want to escape markers and delimiters in texts you can do that by simply escaping them with a single "\" in front of them:

interpolator.addFunction('escapedfunction', "not!");

// "This is an $escapedfunction() and this is not!"
interpolator.process("This is an \$escapedfunction() and this is $escapedfunction(), {})"

You can adjust markers and delimiters via the options when instantiating a StringInterpolator object

Options

StringInterpolator objects can be instantiated with different options:

const interpolator = new StringInterpolator({
    maxDepth: 10,
    marker: '$',
    delimiters: '()',
    log: false,
});
  • maxDepth: Maximum recursion depth
    • Range: 1 - 50
    • Default: 10
  • marker: The marker used to identify interpolation variables and functions
    • Possible: '$', '?', '!', '/', '&', '#', '@', '+', '*', 'Β§', '%'
    • Default: '$'
  • delimiters: The left and right delimiters for functions
    • Possible: '()', '[]', '{}', '<>'
    • Default: '()'
  • log: If error logging should be activated, logs failed interpolation attempts
    • Default: false

Interpolating

After a StringInterpolator object is set up with variables and functions you can start interpolating text by calling the process() method and providing the text and data object.

const interpolator = new StringInterpolator();

// Add variables and functions...

const data = {
  some: 'data',
};

const text = 'Some text with some $some...';

const result = interpolator.process(text, data);

// Some text with some data...
console.log(result);

πŸ“– Examples

Here are some simple to intermediate examples

Example 1 - Variable

const StringInterpolator = require('@jaielzeus/stringinterpolator');

const interpolator = new StringInterpolator();

interpolator.addVariable('name', (d) => d.name);

const data = {
  name: 'JaielZeus',
};

// "Your name is JaielZeus!"
console.log(interpolator.process('Your name is $name!', data));

Example 2 - Variable + Function

const StringInterpolator = require('@jaielzeus/stringinterpolator');

const interpolator = new StringInterpolator();

interpolator.addVariable('a', (d) => d.a);
interpolator.addVariable('b', (d) => d.b);

interpolator.addFunction('max', (d, c) => Math.max(...c.split(',')));

const data = {
  a: 10,
  b: 20,
};

const string = 'The maximum of a=$a and b=$b is $max($a,$b)!';

// "The maximum of a=10 and b=20 is 20!"
console.log(interpolator.process(string, data));

Example 3 - Intermediate

const StringInterpolator = require('@jaielzeus/stringinterpolator');

const interpolator = new StringInterpolator();

interpolator.addVariable('name', (d) => d.name);
interpolator.addVariable('id', (d) => d.id);
interpolator.addVariable('adminId', (d) => d.adminId);
interpolator.addVariable('year', 2023);
interpolator.addVariable('greeting', 'Greetings, $name!');

interpolator.addFunction('if', (d, c) => {
  const [condition, _if = '', _else = ''] = c.split(';');
  return String(condition).trim() === 'true' ? _if : _else;
});

interpolator.addFunction('equal', (d, c) => {
  const [a, b] = c.split(',');
  return a === b;
});

interpolator.addFunction('authorize', (d) => d.id === d.adminId);

const adminId = 100;

const adminData = {
  name: 'JaielZeus',
  id: 100,
};

const userdata = {
  name: 'RandomGuy',
  id: 999,
};

const string = '$greeting You $if($authorize();are;are not) authorized and $if($equal($id,$adminId);can;cannot) enter!';

// "Greetings, JaielZeus! You are authorized and can enter!"
console.log(interpolator.process(string, { ...adminData, adminId }));

// "Greetings, RandomGuy! You are not authorized and cannot enter!"
console.log(interpolator.process(string, { ...userdata, adminId }));

πŸš— Roadmap

  • βœ… Initial push
  • ❌ Possibility to add regex instead of names for variables and functions maybe
  • ❌ Optional default functions
  • ❌ Tests
  • ❌ Wiki with more examples

See the open issues for a full list of proposed features (and known issues).

🫡 Contributing

Contributions are greatly appreciated. You can either open an issue with the tag "enhancement" or contribute your own code:

  1. Fork the Project
  2. Create your Feature Branch
    $ git checkout -b feature/featurename
  3. Commit your Changes
    $ git commit -m 'Add some featurename'
  4. Push to the Branch
    $ git push origin feature/featurename
  5. Open a Pull Request

©️ License

Distributed under the MIT License. See LICENSE for more information.

πŸ“« Contact

JaielZeus

0.1.6

12 months ago

0.1.5

12 months ago

0.1.4

12 months ago

0.1.3

12 months ago

0.1.2

12 months ago

0.1.1

12 months ago

0.1.0

12 months ago

0.0.1

12 months ago