Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
PluralNumberType,
} from '../parser';
export type MessageFormatFunc =
(args: MessageArg[], options: string[]) => string;
export type MessageFormatFuncMap = { [name: string]: MessageFormatFunc };
const get = (key: number | string, args: MessageArgs): MessageArg => {
const res: MessageArg = args.named[key];
return res !== undefined ? res : (typeof key === 'number' ? args.positional[key] : undefined);
};
// Save a bit of processing of common exact matches
const DECIMAL_EXACT: { [n: string]: Decimal } = {
0: DecimalConstants.ZERO,
1: DecimalConstants.ONE,
2: DecimalConstants.TWO
};
/**
* Evaluates a message format against a set of arguments, producing a string.
*/
export class MessageEngine {
private buf: string = '';
constructor(
private plurals: PluralRules,
private formatters: MessageFormatFuncMap,
private code: MessageCode) { }
export const asdecimal = (arg: MessageArg): Decimal => {
switch (typeof arg) {
case 'string':
try {
return new Decimal(arg);
} catch (e) {
return DecimalConstants.NAN;
}
case 'number':
return new Decimal(arg);
case 'boolean':
return arg ? DecimalConstants.ONE : DecimalConstants.ZERO;
case 'object':
if (arg instanceof Decimal) {
return arg;
}
break;
}
return DecimalConstants.NAN;
};
formatRelativeTimeField(bundle: Bundle, value: DecimalArg, field: RelativeTimeFieldType,
options: RelativeTimeFormatOptions, params: NumberParams,
transform: ContextTransformInfo): string {
const width = options.width || 'wide';
const format: RelativeTimeFields = this.relativeTimes[width] || this.relativeTimes.wide;
const group = options.group === undefined ? true : options.group;
let n = coerceDecimal(value);
n = this.internals.numbers.adjustDecimal(n, options);
const negative = n.isNegative();
if (negative) {
n = n.negate();
}
const iszero = n.compare(DecimalConstants.ZERO) === 0;
let res = '';
if (iszero) {
if (options.alwaysNow || !options.numericOnly) {
res = format.current.get(bundle, field);
}
} else if (!options.numericOnly) {
switch (field) {
case 'hour':
case 'minute':
case 'second':
break;
default:
if (n.compare(DecimalConstants.TWO) === 0) {
const p = negative ? format.previous2.get(bundle, field) : format.next2.get(bundle, field);