|
| 1 | +/** |
| 2 | + * @overview |
| 3 | + * |
| 4 | + * The FTL resolver ships with a number of functions built-in. |
| 5 | + * |
| 6 | + * Each function take two arguments: |
| 7 | + * - args - an array of positional args |
| 8 | + * - opts - an object of key-value args |
| 9 | + * |
| 10 | + * Arguments to functions are guaranteed to already be instances of |
| 11 | + * `FluentValue`. Functions must return `FluentValues` as well. |
| 12 | + */ |
| 13 | + |
| 14 | +import { |
| 15 | + FluentValue, |
| 16 | + FluentNone, |
| 17 | + FluentNumber, |
| 18 | + FluentDateTime |
| 19 | +} from "./types.js"; |
| 20 | + |
| 21 | +function values(opts: Record<string, FluentValue>): Record<string, unknown> { |
| 22 | + const unwrapped: Record<string, unknown> = {}; |
| 23 | + for (const [name, opt] of Object.entries(opts)) { |
| 24 | + unwrapped[name] = opt.valueOf(); |
| 25 | + } |
| 26 | + return unwrapped; |
| 27 | +} |
| 28 | + |
| 29 | +export function NUMBER( |
| 30 | + args: Array<FluentValue>, |
| 31 | + opts: Record<string, FluentValue> |
| 32 | +): FluentValue { |
| 33 | + let arg = args[0]; |
| 34 | + |
| 35 | + if (arg instanceof FluentNone) { |
| 36 | + return new FluentNone(`NUMBER(${arg.valueOf()})`); |
| 37 | + } |
| 38 | + |
| 39 | + if (arg instanceof FluentNumber || arg instanceof FluentDateTime) { |
| 40 | + return new FluentNumber(arg.valueOf(), { ...arg.opts, ...values(opts) }); |
| 41 | + } |
| 42 | + |
| 43 | + throw new TypeError("Invalid argument to NUMBER"); |
| 44 | +} |
| 45 | + |
| 46 | +export function DATETIME( |
| 47 | + args: Array<FluentValue>, |
| 48 | + opts: Record<string, FluentValue> |
| 49 | +): FluentValue { |
| 50 | + let arg = args[0]; |
| 51 | + |
| 52 | + if (arg instanceof FluentNone) { |
| 53 | + return new FluentNone(`DATETIME(${arg.valueOf()})`); |
| 54 | + } |
| 55 | + |
| 56 | + if (arg instanceof FluentNumber || arg instanceof FluentDateTime) { |
| 57 | + return new FluentDateTime(arg.valueOf(), { ...arg.opts, ...values(opts) }); |
| 58 | + } |
| 59 | + |
| 60 | + throw new TypeError("Invalid argument to DATETIME"); |
| 61 | +} |
0 commit comments