npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@jaielzeus/stringinterpolator

v0.1.6

Published

String interpolation for texts using variable and function tokens

Downloads

4

Readme

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