idillon | ae655dd | 2022-10-14 18:11:02 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2022 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU Affero General Public License as |
| 6 | * published by the Free Software Foundation; either version 3 of the |
| 7 | * License, or (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU Affero General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Affero General Public |
| 15 | * License along with this program. If not, see |
| 16 | * <https://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | export type Interpolations = Record<string, string>; |
| 20 | |
| 21 | export interface TranslateEnumerationOptions<T> { |
| 22 | // partial i18next interpolation key to which an index will be added |
| 23 | elementPartialKey: string; |
| 24 | // function to retrieve the i18next interpolation value |
| 25 | getElementValue: (element: T) => string; |
| 26 | // functions to translate the enumeration according to the number of elements |
| 27 | // The index of the function corresponds to the number of elements in the enumeration |
| 28 | // If the number of elements is higher than the number of functions, then the last function of the array will be used |
| 29 | translaters: ((interpolations: Interpolations) => string)[]; |
| 30 | } |
| 31 | |
| 32 | export const translateEnumeration = <T>(list: T[], options: TranslateEnumerationOptions<T>): string => { |
| 33 | const quantity = list.length; |
| 34 | const max = options.translaters.length; |
| 35 | |
| 36 | const interpolations: Interpolations = {}; |
| 37 | |
| 38 | for (let i = 0; i < quantity && i < max; i++) { |
| 39 | const elementKey = `${options.elementPartialKey}${i}`; |
| 40 | interpolations[elementKey] = options.getElementValue(list[i]); |
| 41 | } |
| 42 | |
idillon | 3e378fd | 2022-12-23 11:48:12 -0500 | [diff] [blame] | 43 | interpolations.excess = (quantity - max + 2).toString(); |
idillon | ae655dd | 2022-10-14 18:11:02 -0400 | [diff] [blame] | 44 | |
idillon | 3e378fd | 2022-12-23 11:48:12 -0500 | [diff] [blame] | 45 | const translaterIndex = quantity < max ? quantity : max - 1; |
idillon | ae655dd | 2022-10-14 18:11:02 -0400 | [diff] [blame] | 46 | |
| 47 | return options.translaters[translaterIndex](interpolations); |
| 48 | }; |