0.0.1005 β€’ Published 7 months ago

@js-utility/template-engine v0.0.1005

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

Transform Engine

A lightweight, flexible string transformation engine for JavaScript and TypeScript. Transform Engine enables dynamic string interpolation, inline expressions, and powerful formatting with a clean, customizable syntax.

If this package has been helpful to you, your support goes a long way in helping maintain it, improve its features, and build more open-source tools like it. Buy Me a Coffee β˜•


✨ Features

  • Inline Expressions: Use {{ ... }} to embed dynamic expressions directly in your strings.
  • Built-in Methods: Perform calculations, string manipulations, and more with a rich set of built-in methods.
  • Chained Formatters: Pipe results through formatters for advanced formatting.
  • Customizable & Extensible: Easily extend with your own methods and formatters (API coming soon).
  • Zero Dependencies: Lightweight and fast, suitable for any project.
  • AI Generated, well formatted & well tested: Unit tested with automation testing and verified by humans. It is type safe, null safe.

πŸ“¦ Installation

npm install @js-utility/template-engine

πŸš€ Usage

import { TransformEngine } from '@js-utility/template-engine';

const input = 'Total: {{ sum:10:20 | currency "US":2 }}';

const output = TransformEngine(input, {});

console.log(output); // Total: $30.00

🧠 Syntax

Each placeholder follows this pattern:

{{ method:param1:param2 | formatter:param1:param2 }}
  • method: The function to execute (e.g., sum, row.name)
  • params: (Optional) Arguments to the method (numbers, strings, variables), separated by colons (:)
  • formatter: (Optional) Pipe output through a formatter (e.g., currency, capitalize)
  • formatParams: (Optional) Arguments to the formatter (numbers, strings, variables), separated by colons (:)

Examples:

{{ sum:2:3 }}                       => 5
{{ row.name | capitalize }}         => John doe
{{ row.amount | currency 'US':2 }}  => $1,234.57
{{ sum:10:20 | number 'US':1 }}     => 30.0
{{ 0.25 | percentage 2 }}           => 25.00%

πŸ“˜ API

FunctionDescription
TransformEngine(text: string, context?: object, options?: object): stringTransforms the input string by evaluating all placeholders.

Parameters

NameTypeDescription
textstringThe input string containing placeholders.
contextobject(Optional) Data object for expression resolution.
optionsobject(Optional) Reference Resolution Parameter, that supports context format to key value pair for references. It is default to off.

Returns:
string β€” The transformed string with all placeholders evaluated.


πŸ› οΈ Built-in Methods

MethodDescription
sumAdds all arguments
subtractSubtracts numbers
avgReturns average
minMinimum value
maxMaximum value
countCounts number of items
multiplyMultiplies all numbers
divideDivides numbers
concatConcatenates strings
modModulo
powExponentiation
absAbsolute value
floorRounds down
ceilRounds up
sqrtSquare root
logNatural logarithm
echoReturns the first argument
lengthLength of string or array
sizeAlias of length

🎨 Built-in Formatters

FormatterDescription
upperConverts to uppercase
lowerConverts to lowercase
roundRounds to nearest integer
numberFormats number with fraction points (e.g., number 'US':1:2)
dateFormats as date
currencyFormats as currency (e.g., currency "US":0:2 for country and decimals)
percentageFormats as percent (e.g., percentage 0:2 for decimals)
jsonConverts to JSON string
capitalizeCapitalizes the first letter
trimTrims whitespace
lengthGets length of string or array
camelConverts to camelCase
snakeConverts to snake_case
stripRemoves non-alphanumerics
prefixAdds a prefix (e.g., prefix:"ID-")
suffixAdds a suffix
repeatRepeats a string (e.g., repeat:3)
titleConverts to Title Case

Note:

  • currency and number use the same parameter structure:
    formatter alpha_2_country_code:min_fraction:max_fraction
    • alpha_2_country_code: e.g., "US"
    • min_fraction (optional): Minimum Number of decimal places. default to '0'
    • max_fraction (optional): Maximum Number of decimal places. default to 'min_fraction'

🧩 Placeholder Regex

const PLACEHOLDER_REGEX = /\{\{\s*([^\s|}]+)(?:\s+([^|}]*?))?(?:\s*\|\s*([^\s|}]+)(?:\s+([^}]*?))?)?\s*\}\}/g;
  • Supports: {{ method args | formatter params }}
  • Flexible whitespace and quoted string arguments ("...", '...')

πŸ“š Examples

TransformEngine('Hello {{ row.name | capitalize }}!', { row: { name: 'sarah' } });
// => Hello Sarah!

TransformEngine('Price: {{ sum 10:15 | currency "US":2 }}');
// => Price: $25.00

TransformEngine('{{ echo "hello world" | upper }}');
// => HELLO WORLD

TransformEngine('Value: {{ sum 1520.856:864.69 | currency "US":1 }}');
// => Value: $2,385.5

TransformEngine('Percent: {{ 0.8320 | percentage 1 }}');
// => Percent: 83.2%

πŸ“˜ TypeScript Support

This package is built with full TypeScript support. All functions are type-safe, and type definitions are bundled, so you get autocomplete, inline documentation, and compile-time safety out of the box, no need to install @types.


πŸ§ͺ Testing

This package is thoroughly tested using Jest, with a focus on correctness, edge cases, and null-safety.


🀝 Contributing

This project is maintained privately. While direct contributions (e.g., pull requests or code changes) are not open to the public, feedback, suggestions, and issue reports are always welcome.

If you notice any bugs, edge cases, or have ideas for improvement, feel free to reach out or open an issue (if access is available). Your input helps make the package more robust and useful for everyone!


πŸ’– Support / Donate

If you find this package useful, consider supporting its development. Your support helps maintain the project, improve documentation, and add new features.

Support as through :


πŸ’¬ Support & Feedback

Have ideas, suggestions, or found a bug? I'd love to hear from you!

  • Feedback: Whether it’s a feature request or an edge case you'd like handled, your input helps improve the package.
  • Issues: If you run into a bug or unexpected behavior, feel free to open an issue (if the repo is accessible).
  • Reach Out: You can also reach out directly for feedback or discussion via email or the contact details in the repository.

Your feedback helps shape better tools for everyone using this package.