UNPKG

messageformat

Version:

Intl.MessageFormat / Unicode MessageFormat 2 parser, runtime and polyfill

72 lines (71 loc) 2.91 kB
import { MessageFunctionError } from "../errors.js"; import { getMessageNumber, readNumericOperand } from "./number.js"; import { asPositiveInteger, asString } from "./utils.js"; /** * `currency` accepts as input numerical values as well as * objects wrapping a numerical value that also include a `currency` property. * * @beta */ export function currency(ctx, exprOpt, operand) { const input = readNumericOperand(operand); const options = Object.assign({}, input.options, { localeMatcher: ctx.localeMatcher, style: 'currency' }); for (const [name, optval] of Object.entries(exprOpt)) { if (optval === undefined) continue; try { switch (name) { case 'currency': case 'currencySign': case 'roundingMode': case 'roundingPriority': case 'trailingZeroDisplay': case 'useGrouping': // @ts-expect-error Let Intl.NumberFormat construction fail options[name] = asString(optval); break; case 'minimumIntegerDigits': case 'minimumSignificantDigits': case 'maximumSignificantDigits': case 'roundingIncrement': // @ts-expect-error TS types don't know about roundingIncrement options[name] = asPositiveInteger(optval); break; case 'currencyDisplay': { const strval = asString(optval); if (strval === 'never') { ctx.onError('unsupported-operation', 'Currency display "never" is not yet supported'); } else { // @ts-expect-error Let Intl.NumberFormat construction fail options[name] = strval; } break; } case 'fractionDigits': { const strval = asString(optval); if (strval === 'auto') { options.minimumFractionDigits = undefined; options.maximumFractionDigits = undefined; } else { const numval = asPositiveInteger(strval); options.minimumFractionDigits = numval; options.maximumFractionDigits = numval; } break; } } } catch { ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`); } } if (!options.currency) { throw new MessageFunctionError('bad-operand', 'A currency code is required for :currency'); } return getMessageNumber(ctx, input.value, options, false); }