UNPKG

voca

Version:

The ultimate JavaScript string library

103 lines (85 loc) 2.69 kB
import './internal/is_nil.js'; import isString from './is_string.js'; import { c as coerceToString } from './internal/coerce_to_string.js'; import { n as nilDefault } from './internal/nil_default.js'; import { a as _slicedToArray } from './internal/_rollupPluginBabelHelpers.js'; /** * Translates characters or replaces substrings in `subject`. * * @function tr * @static * @since 1.3.0 * @memberOf Manipulate * @param {string} [subject=''] The string to translate. * @param {string|Object} from The string of characters to translate from. Or an object, then the object keys are replaced with corresponding values (longest keys are tried first). * @param {string} to The string of characters to translate to. Ignored when `from` is an object. * @return {string} Returns the translated string. * @example * v.tr('hello', 'el', 'ip'); * // => 'hippo' * * v.tr('légèreté', 'éè', 'ee'); * // => 'legerete' * * v.tr('Yes. The fire rises.', { * 'Yes': 'Awesome', * 'fire': 'flame' * }) * // => 'Awesome. The flame rises.' * * v.tr(':where is the birthplace of :what', { * ':where': 'Africa', * ':what': 'Humanity' * }); * // => 'Africa is the birthplace of Humanity' * */ function tr(subject, from, to) { var subjectString = coerceToString(subject); var keys; var values; if (isString(from) && isString(to)) { keys = from.split(''); values = to.split(''); } else { var _extractKeysAndValues = extractKeysAndValues(nilDefault(from, {})); var _extractKeysAndValues2 = _slicedToArray(_extractKeysAndValues, 2); keys = _extractKeysAndValues2[0]; values = _extractKeysAndValues2[1]; } var keysLength = keys.length; if (keysLength === 0) { return subjectString; } var result = ''; var valuesLength = values.length; for (var index = 0; index < subjectString.length; index++) { var isMatch = false; var matchValue = void 0; for (var keyIndex = 0; keyIndex < keysLength && keyIndex < valuesLength; keyIndex++) { var key = keys[keyIndex]; if (subjectString.substr(index, key.length) === key) { isMatch = true; matchValue = values[keyIndex]; index = index + key.length - 1; break; } } result += isMatch ? matchValue : subjectString[index]; } return result; } function extractKeysAndValues(object) { var keys = Object.keys(object); var values = keys.sort(sortStringByLength).map(function (key) { return object[key]; }); return [keys, values]; } function sortStringByLength(str1, str2) { if (str1.length === str2.length) { return 0; } return str1.length < str2.length ? 1 : -1; } export default tr;