blob: 4a559a56e85a95190899b7663078757e9f4e15a7 [file] [log] [blame]
idillonae655dd2022-10-14 18:11:02 -04001/*
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
19export type Interpolations = Record<string, string>;
20
21export 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
32export 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
43 interpolations.excess = (max - quantity + 1).toString();
44
45 const translaterIndex = quantity <= max ? quantity : max;
46
47 return options.translaters[translaterIndex](interpolations);
48};