Skip to main content
Version: 1.10.1

MessageEngine

Evalutes a parsed message against one or more arguments.

new

Constructs a new message engine.

Syntax

new MessageEngine(plurals, converters, formatters, code)

Parameters

evaluate

Evaluate a parsed message against one or more arguments. Arguments can be positional or named.

Syntax

evaluate(positional: MessageArg[], named: MessageNamedArgs): string

Parameters

  • positional: MessageArg[]
    • Arguments keyed by their position in the array
  • named: MessageNamedArgs
    • Arguments keyed by name

Example

import {
buildMessageMatcher,
parseMessagePattern,
DefaultMessageArgConverter,
MessageArg,
MessageEngine,
MessageNamedArgs
} from '@phensley/messageformat';
import { pluralRules } from '@phensley/plurals';

const FORMATTERS = {
foo: (args: MessageArg[], options: string[]) =>
options[0] === 'upper' ? args[0].toUpperCase() : args[1].toLowerCase()
};
const NAMES = Object.keys(FORMATTERS);
const MATCHER = buildMessageMatcher(NAMES);
const CONVERTER = new DefaultMessageArgConverter();

const parse = (message: string) => parseMessagePattern(message, MATCHER);

const format = (
message: string,
positional: MessageArg[],
named: MessageNamedArgs = {}
) => {
const plurals = pluralRules.get('en');
const engine = new MessageEngine(
plurals,
CONVERTER,
FORMATTERS,
parse(message)
);
log(engine.evaluate(positional, named));
};

const msg =
'{0, plural, offset:1 =0 {Be the first to like this} =1 {You liked this} ' +
'one {You and someone else liked this} other {You and # others liked this}}';

format(msg, [0]);
format(msg, [1]);
format(msg, [2]);
format(msg, [3]);
Be the first to like this
You liked this
You and someone else liked this
You and 2 others liked this