voca
Version:
The ultimate JavaScript string library
105 lines (86 loc) • 2.77 kB
JavaScript
;
require('./internal/is_nil.js');
var is_string = require('./is_string.js');
var coerce_to_string = require('./internal/coerce_to_string.js');
var nil_default = require('./internal/nil_default.js');
var _rollupPluginBabelHelpers = require('./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 = coerce_to_string.coerceToString(subject);
var keys;
var values;
if (is_string(from) && is_string(to)) {
keys = from.split('');
values = to.split('');
} else {
var _extractKeysAndValues = extractKeysAndValues(nil_default.nilDefault(from, {}));
var _extractKeysAndValues2 = _rollupPluginBabelHelpers._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;
}
module.exports = tr;