|
| 1 | +import { getPluralIndex } from './utils/get-plural-index' |
| 2 | + |
| 3 | +/** |
| 4 | + * Select a proper translation string based on the given number. |
| 5 | + */ |
| 6 | +export function choose(message: string, number: number, lang: string): string { |
| 7 | + let segments = message.split('|') |
| 8 | + const extracted = extract(segments, number) |
| 9 | + |
| 10 | + if (extracted !== null) { |
| 11 | + return extracted.trim() |
| 12 | + } |
| 13 | + |
| 14 | + segments = stripConditions(segments) |
| 15 | + const pluralIndex = getPluralIndex(lang, number) |
| 16 | + |
| 17 | + if (segments.length === 1 || !segments[pluralIndex]) { |
| 18 | + return segments[0] |
| 19 | + } |
| 20 | + |
| 21 | + return segments[pluralIndex] |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Extract a translation string using inline conditions. |
| 26 | + */ |
| 27 | +function extract(segments: string[], number: number): string | null { |
| 28 | + for (const part of segments) { |
| 29 | + let line = extractFromString(part, number) |
| 30 | + |
| 31 | + if (line !== null) { |
| 32 | + return line |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return null |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Get the translation string if the condition matches. |
| 41 | + */ |
| 42 | +function extractFromString(part: string, number: number): string | null { |
| 43 | + const matches = part.match(/^[\{\[]([^\[\]\{\}]*)[\}\]](.*)/s) || [] |
| 44 | + if (matches.length !== 3) { |
| 45 | + return null |
| 46 | + } |
| 47 | + |
| 48 | + const condition = matches[1] |
| 49 | + const value = matches[2] |
| 50 | + |
| 51 | + if (condition.includes(',')) { |
| 52 | + let [from, to] = condition.split(',') |
| 53 | + |
| 54 | + if (to === '*' && number >= parseFloat(from)) { |
| 55 | + return value |
| 56 | + } else if (from === '*' && number <= parseFloat(to)) { |
| 57 | + return value |
| 58 | + } else if (number >= parseFloat(from) && number <= parseFloat(to)) { |
| 59 | + return value |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return parseFloat(condition) === number ? value : null |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Strip the inline conditions from each segment, just leaving the text. |
| 68 | + */ |
| 69 | +function stripConditions(segments: string[]): string[] { |
| 70 | + return segments.map((part) => part.replace(/^[\{\[]([^\[\]\{\}]*)[\}\]]/, '')) |
| 71 | +} |
0 commit comments