UNPKG

custom-string-formatter

Version:
114 lines (113 loc) 2.98 kB
import { IFormatter } from './protocol'; /** * Creates a formatter function. * * @returns * A function that formats a string from an object-parameter, and according to the specified configurator. * * @example * import {createFormatter, IFormatter} from 'custom-string-formatter'; * * class BaseFormatter implements IFormatter { * format(value: any): string { * return (value ?? 'null').toString(); * } * } * * const format = createFormatter(new BaseFormatter()); * * format('Hello ${title} ${name}!', {title: 'Mr.', name: 'Foreman'}); * //=> Hello Mr. Foreman! * * @example * // Function createFormatter expects only an interface, * // so using a class is not really necessary: * * const format = createFormatter({ * format(value: any): string { * return (value ?? 'null').toString(); * } * }); */ export declare function createFormatter(base: IFormatter): (text: string, params: { [key: string]: any; }) => string; /** * A fast check if a string has valid variables in it. * * @returns * Boolean flag, indicating if the string has valid variables in it. * * @example * import {hasVariables} from 'custom-string-formatter'; * * hasVariables('${value}'); //=> true * * hasVariables('some text'); //=> false * * @see {@link countVariables}, {@link enumVariables} */ export declare function hasVariables(text: string): boolean; /** * A fast count of valid variables in a string. * * @returns * Number of valid variables in the string. * * @example * import {countVariables} from 'custom-string-formatter'; * * countVariables('some text'); //=> 0 * * countVariables('${first} ${second}'); //=> 2 * * @see {@link hasVariables}, {@link enumVariables} */ export declare function countVariables(text: string): number; /** * Variable descriptor, as returned from {@link enumVariables} function. */ export interface IVariable { /** * Exact enumeration match for the variable. */ match: string; /** * Extracted property name. */ property: string; /** * Extracted filters with raw arguments (not decoded). */ filters: Array<{ name: string; args: string[]; }>; } /** * Enumerates and parses variables from a string, for any kind of reference analysis. * * @param text * Text string with variables. * * @returns IVariable[] * An array of matched variables (as descriptors) * * @example * import {enumVariables} from 'custom-string-formatter'; * * enumVariables('${title} ${name} address: ${address | json}'); * // ==> * [ * {match: '${title}', property: 'title', filters: []}, * {match: '${name}', property: 'name', filters: []}, * { * match: '${address | json}', * property: 'address', * filters: [{name: 'json', args: []}] * } * ] * * @see {@link hasVariables}, {@link countVariables} */ export declare function enumVariables(text: string): IVariable[];