Transformer

The transformer class is a swiss army knife for manipulating values. especially in combination with the pipe, processing chains can be built up.

Import
the javascript logo
import { Transformer } from "@schukai/monster/source/data/transformer.mjs";
Source
the git logo
Package
the npm logo
Since
1.5.0

Transformer

The `Transformer` class is used to transform data. The transformation is defined as a string.

The following transformations are available:

CommandParameterAliasDescription
callfunction:param1:param2:...Calling a callback function. The function can be defined in three places: either globally, in the context addCallback or in the passed object
concatpath or static:path or static:...This function concatenates the values of the passed paths. If no value in the path is found, the path is used as a static value.
containsChecks if an array or string contains a value (since 3.17)
currencymaximumFractionDigits:roundingIncrementmoneyConvert a currency and amount to a local string (since 3.17)
dateConvert a date string to a localized date string (since 3.16)
datetimeConvert a date string to a localized date-time string (since 3.17)
dayReturns the day of a date (since 3.16)
debugThe passed value is output (console) and returned
defaultvalue:type??If the value is undefined the first argument is returned, otherwise the value. The third optional parameter specifies the desired type. If no type is specified, string is used. Valid types are bool, string, int, float, undefined and object. An object default value must be specified as a base64 encoded json string. (since 1.12)
element-by-idplainAll HTML tags are removed (*)
emptyReturn empty String ""
equalsvalueCompare the comparison value with the specified value and return true if they match.
first-keydefaultCan be applied to objects and returns the value of the first key. All keys of the object are fetched and sorted. (since 1.23)
from-base64atobConverts the value from base64
fromjsonType conversion from a JSON string (since 1.12)
has-entrieshasentriesChecks whether an array or an object has elements. (since 3.17)
hourshourReturns the hours of a date (since 3.16)
ifstatement1:statement2?Is the ternary operator, the first parameter is the valid statement, the second is the false part. To use the current value in the queue, you can set the value keyword. On the other hand, if you want to have the static string "value", you have to put one backslash \\ in front of it and write value. the follow values are true: 'on', true, 'true'. If you want to have a space, you also have to write \\ in front of the space.
indexkey:defaultproperty, keyFetches a value from an object, an array, a map or a set
is-arrayisarrayChecks if the value is a array (since 3.17)
is-floatisfloatChecks if the value is a float (since 3.17)
is-nullisnullChecks if the value is null (since 3.17)
is-numberisnumberChecks if the value is a number (since 3.17)
is-objectisobjectChecks if the value is a object (since 3.17)
is-setissetChecks if the value is undefined and not null (since 3.17)
is-undefinedisundefinedChecks if the value is undefined (since 3.17)
last-keydefaultCan be applied to objects and returns the value of the last key. All keys of the object are fetched and sorted. (since 1.23)
lengthcountLength of the string or entries of an array or object
mapkey:value:key:value....Map a value with an existing mapping (since 3.16)
minutesminuteReturns the minutes of a date (since 3.16)
monthReturns the month of a date (since 3.16)
nopDo nothing
notConverts a bolian value into the opposite one (since 3.17)
nth-keyindex:defaultCan be applied to objects and returns the value of the nth key. All keys of the object are fetched and sorted. (since 1.23)
nth-last-keyindex:defaultCan be applied to objects and returns the value of the nth key from behind. All keys of the object are fetched and sorted. (since 1.23)
path-existspathCheck if the specified path is available in the value (since 1.24)
pathpathThe access to an object is done via a Pathfinder object
plaintextplainAll HTML tags are removed ➊
prefixtextAdds a prefix
rawurlencodeURL coding
secondssecondReturns the seconds of a date (since 3.16)
staticnoneThe Arguments value is used and passed to the value. Special characters \and : can be quotet by a preceding \.
substringstart:lengthReturns a substring
suffixtextAdds a suffix
timeConvert a date string to a localized time string (since 3.16)
timestampConvert a date string to a time stamp (since 3.16)
to-base64base64, btobConverts the value to base64
tointegerType conversion to an integer value
tojsonType conversion to a JSON string (since 1.8)
tolowerstrtolower, tolowercaseThe input value is converted to lowercase letters
tostringType conversion to a string.
toupperstrtoupper, touppercaseThe input value is converted to uppercase letters
translationkey:defaulti18nTranslations can be applied. The translations must be stored in the DOM. (*) To use the current value as key the first parameter must be set to undefined.
trimRemove spaces at the beginning and end
ucfirstFirst character large
ucwordsAny word beginning large
undefinedReturn undefined
uniqidCreates a string with a unique value ➋
weekdayReturns the day of the week of a date (since 3.16)
yearConvert a date string to a year (since 3.16)

➊ for this functionality the extension jsdom must be loaded in the nodejs context.



if (typeof window !== "object") {
    const {window} = new JSDOM('', {
        url: 'http://example.com/',
        pretendToBeVisual: true
    });
    
    [
        'self',
        'document',
        'Node',
        'Element',
        'HTMLElement',
        'DocumentFragment',
        'DOMParser',
        'XMLSerializer',
        'NodeFilter',
        'InputEvent',
        'CustomEvent',
    ].forEach(key => (global[key] = window[key]));
}

➋ for this command the crypt library is necessary in the nodejs context.


    import * as Crypto from "@peculiar/webcrypto";

    global['crypto'] = new Crypto.Crypto();

With the method `setCallback(name, callback, context)` you can define your own transformation functions. The context parameter is optional and can be used to define the context in which the callback function is called. If no context is specified, the global context is used. In the pipe the name of the callback function is used by prefixing it with a `call:`.


import {Transformer} from '@schukai/monster/source/data/transformer.mjs';

const transformer = new Transformer("call:myCallback");
transformer.setCallback("myCallback", function (value) {
    return value + " world";
});
console.log(transformer.run("hello")); // hello world
    

Simple

// This is a simple example of how the Transformer class can be used. In this case, 
// the `tolower` function is used to convert a string to lowercase. There are a 
// variety of transformers available for different purposes.

import {Transformer} from '@schukai/monster/source/data/transformer.mjs';

const transformer1 = new Transformer("tolower")

console.log(transformer1.run("HELLO"))
// ↦ hello

console.log(transformer1.run("WORLD"))
// ↦ world


// In the next example, the `length` function is used to return the length of a string.

const transformer2 = new Transformer("length")


console.log(transformer2.run("HELLO"))
// ↦ 5

console.log(transformer2.run("WORLD"))
// ↦ 5

// In the next example, the `substring` function is used to return a substring of a string.
// The `substring` function takes two arguments: the start index and the end index.

const transformer3 = new Transformer("substring:1,3")

console.log(transformer3.run("HELLO"))
// ↦ ELL

console.log(transformer3.run("WORLD"))
// ↦ ORL

Exported

Transformer

Derived from

Base

Options

The Options listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits Options from these parent classes. If you cannot find a specific Options in this list, we recommend consulting the documentation of the Base.

Option
Type
Default
Description
-/-

Properties

The Properties listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits Properties from these parent classes. If you cannot find a specific Properties in this list, we recommend consulting the documentation of the Base.

Methods

The methods listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits methods from these parent classes. If you cannot find a specific method in this list, we recommend consulting the documentation of the Base.

Constructor

constructor(definition)
Parameters
  • definition {string}: definition

Structural methods

setCallback(name,callback,context)
Parameters
  • name {string}: name
  • callback {function}: callback
  • context {object}: context
Returns
  • {Transformer}
Throws
  • {TypeError} value is not a string
  • {TypeError} value is not a function

Other methods

run(value)
Parameters
  • value {*}: value
Returns
  • {*}
Throws
  • {Error} unknown command
  • {TypeError} unsupported type
  • {Error} type not supported

Events

This component does not fire any public events. It may fire events that are inherited from its parent classes.

The current width of the area is too small to display the content correctly.