All Downloads are FREE. Search and download functionalities are using the official Maven repository.

META-INF.resources.js.utils.language.es.js Maven / Gradle / Ivy

The newest version!
/**
 * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com
 * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
 */

const SPLIT_REGEX = /({\d+})/g;

/**
 * Uses the singular language key if the count is 1. Otherwise uses the plural
 * language key.
 * @param {string} singular The language key in singular form.
 * @param {string} plural The language key in plural form.
 * @param {number} count The amount to display in the message.
 * @param {boolean} toString If the message should be converted to a string.
 * @return {(string|Array)} The translated message.
 */
export function getPluralMessage(singular, plural, count = 0, toString) {
	const message = count === 1 ? singular : plural;

	return sub(message, [count], toString);
}

/**
 * Utility function for substituting variables into language keys.
 *
 * Examples:
 * sub(Liferay.Language.get('search-x'), ['all'])
 * => 'search all'
 * sub(Liferay.Language.get('search-x'), [all], false)
 * => 'search all'
 *
 * @param {string} langKey This is the language key used from our properties file
 * @param {string} args Arguments to pass into language key
 * @param {string} join Boolean used to indicate whether to call `.join()` on
 * the array before it is returned. Use `false` if subbing in JSX.
 * @return {(string|Array)}
 */
export function sub(langKey, args, join = true) {
	const keyArray = langKey
		.split(SPLIT_REGEX)
		.filter((val) => val.length !== 0);

	for (let i = 0; i < args.length; i++) {
		const arg = args[i];

		const indexKey = `{${i}}`;

		let argIndex = keyArray.indexOf(indexKey);

		while (argIndex >= 0) {
			keyArray.splice(argIndex, 1, arg);

			argIndex = keyArray.indexOf(indexKey);
		}
	}

	return join ? keyArray.join('') : keyArray;
}