Skip to content

Commit

Permalink
perf: Use optional chaining
Browse files Browse the repository at this point in the history
  • Loading branch information
VIKTORVAV99 committed May 10, 2024
1 parent 9ce9150 commit 00ff5d5
Show file tree
Hide file tree
Showing 11 changed files with 39 additions and 50 deletions.
11 changes: 4 additions & 7 deletions src/BackendConnector.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ class Connector extends EventEmitter {
this.state = {};
this.queue = [];

if (this.backend && this.backend.init) {
this.backend.init(services, options.backend, options);
}
this.backend?.init?.(services, options.backend, options);
}

queueLoad(languages, namespaces, options, callback) {
Expand Down Expand Up @@ -234,9 +232,8 @@ class Connector extends EventEmitter {

saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
if (
this.services.utils &&
this.services.utils.hasLoadedNamespace &&
!this.services.utils.hasLoadedNamespace(namespace)
this.services?.utils?.hasLoadedNamespace &&
!this.services?.utils?.hasLoadedNamespace(namespace)
) {
this.logger.warn(
`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`,
Expand All @@ -248,7 +245,7 @@ class Connector extends EventEmitter {
// ignore non valid keys
if (key === undefined || key === null || key === '') return;

if (this.backend && this.backend.create) {
if (this.backend?.create) {
const opts = {
...options,
isUpdate,
Expand Down
4 changes: 1 addition & 3 deletions src/Formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,7 @@ class Formatter {
let formatted = mem;
try {
// options passed explicit for that formatted value
const valOptions =
(options && options.formatParams && options.formatParams[options.interpolationkey]) ||
{};
const valOptions = options?.formatParams?.[options.interpolationkey] || {};

// language
const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
Expand Down
10 changes: 5 additions & 5 deletions src/Interpolator.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Interpolator {
this.logger = baseLogger.create('interpolator');

this.options = options;
this.format = (options.interpolation && options.interpolation.format) || ((value) => value);
this.format = options.interpolation?.format || ((value) => value);
this.init(options);
}

Expand Down Expand Up @@ -84,7 +84,7 @@ class Interpolator {

resetRegExp() {
const getOrResetRegExp = (existingRegExp, pattern) => {
if (existingRegExp && existingRegExp.source === pattern) {
if (existingRegExp?.source === pattern) {
existingRegExp.lastIndex = 0;
return existingRegExp;
}
Expand Down Expand Up @@ -154,10 +154,10 @@ class Interpolator {
this.resetRegExp();

const missingInterpolationHandler =
(options && options.missingInterpolationHandler) || this.options.missingInterpolationHandler;
options?.missingInterpolationHandler || this.options.missingInterpolationHandler;

const skipOnVariables =
options && options.interpolation && options.interpolation.skipOnVariables !== undefined
options?.interpolation?.skipOnVariables !== undefined
? options.interpolation.skipOnVariables
: this.options.interpolation.skipOnVariables;

Expand Down Expand Up @@ -231,7 +231,7 @@ class Interpolator {
const matchedSingleQuotes = optionsString.match(/'/g);
const matchedDoubleQuotes = optionsString.match(/"/g);
if (
(matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes) ||
((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes) ||
matchedDoubleQuotes.length % 2 !== 0
) {
optionsString = optionsString.replace(/'/g, '"');
Expand Down
4 changes: 2 additions & 2 deletions src/PluralResolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,10 @@ class PluralResolver {
const rule = this.getRule(code, options);

if (this.shouldUseIntlApi()) {
return rule && rule.resolvedOptions().pluralCategories.length > 1;
return rule?.resolvedOptions().pluralCategories.length > 1;
}

return rule && rule.numbers.length > 1;
return rule?.numbers.length > 1;
}

getPluralFormsOfKey(code, key, options = {}) {
Expand Down
2 changes: 1 addition & 1 deletion src/ResourceStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class ResourceStore extends EventEmitter {
}
if (result || !ignoreJSONStructure || typeof key !== 'string') return result;

return utils.deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
return utils.deepFind(this.data?.[lng]?.[ns], key, keySeparator);
}

addResource(lng, ns, key, value, options = { silent: false }) {
Expand Down
31 changes: 14 additions & 17 deletions src/Translator.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class Translator extends EventEmitter {
}

const resolved = this.resolve(key, options);
return resolved && resolved.res !== undefined;
return resolved?.res !== undefined;
}

extractFromKey(key, options) {
Expand Down Expand Up @@ -111,7 +111,7 @@ class Translator extends EventEmitter {
const lng = options.lng || this.language;
const appendNamespaceToCIMode =
options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
if (lng && lng.toLowerCase() === 'cimode') {
if (lng?.toLowerCase() === 'cimode') {
if (appendNamespaceToCIMode) {
const nsSeparator = options.nsSeparator || this.options.nsSeparator;
if (returnDetails) {
Expand Down Expand Up @@ -142,9 +142,9 @@ class Translator extends EventEmitter {

// resolve from store
const resolved = this.resolve(keys, options);
let res = resolved && resolved.res;
const resUsedKey = (resolved && resolved.usedKey) || key;
const resExactUsedKey = (resolved && resolved.exactUsedKey) || key;
let res = resolved?.res;
const resUsedKey = resolved?.usedKey || key;
const resExactUsedKey = resolved?.exactUsedKey || key;

const resType = Object.prototype.toString.apply(res);
const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
Expand Down Expand Up @@ -289,7 +289,7 @@ class Translator extends EventEmitter {
updateMissing,
options,
);
} else if (this.backendConnector && this.backendConnector.saveMissing) {
} else if (this.backendConnector?.saveMissing) {
this.backendConnector.saveMissing(
l,
namespace,
Expand Down Expand Up @@ -353,7 +353,7 @@ class Translator extends EventEmitter {
}

extendTranslation(res, key, options, resolved, lastKey) {
if (this.i18nFormat && this.i18nFormat.parse) {
if (this.i18nFormat?.parse) {
res = this.i18nFormat.parse(
res,
{ ...this.options.interpolation.defaultVariables, ...options },
Expand All @@ -371,7 +371,7 @@ class Translator extends EventEmitter {
});
const skipOnVariables =
typeof res === 'string' &&
(options && options.interpolation && options.interpolation.skipOnVariables !== undefined
(options?.interpolation?.skipOnVariables !== undefined
? options.interpolation.skipOnVariables
: this.options.interpolation.skipOnVariables);
let nestBef;
Expand Down Expand Up @@ -400,7 +400,7 @@ class Translator extends EventEmitter {
res = this.interpolator.nest(
res,
(...args) => {
if (lastKey && lastKey[0] === args[0] && !options.context) {
if (lastKey?.[0] === args[0] && !options.context) {
this.logger.warn(
`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`,
);
Expand All @@ -421,8 +421,7 @@ class Translator extends EventEmitter {
if (
res !== undefined &&
res !== null &&
postProcessorNames &&
postProcessorNames.length &&
postProcessorNames?.length &&
options.applyPostProcessor !== false
) {
res = postProcessor.handle(
Expand Down Expand Up @@ -481,9 +480,8 @@ class Translator extends EventEmitter {

if (
!checkedLoadedFor[`${codes[0]}-${ns}`] &&
this.utils &&
this.utils.hasLoadedNamespace &&
!this.utils.hasLoadedNamespace(usedNS)
this.utils?.hasLoadedNamespace &&
!this.utils?.hasLoadedNamespace(usedNS)
) {
checkedLoadedFor[`${codes[0]}-${ns}`] = true;
this.logger.warn(
Expand All @@ -500,7 +498,7 @@ class Translator extends EventEmitter {

const finalKeys = [key];

if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
if (this.i18nFormat?.addLookupKeys) {
this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
} else {
let pluralSuffix;
Expand Down Expand Up @@ -566,8 +564,7 @@ class Translator extends EventEmitter {
}

getResource(code, ns, key, options = {}) {
if (this.i18nFormat && this.i18nFormat.getResource)
return this.i18nFormat.getResource(code, ns, key, options);
if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
return this.resourceStore.getResource(code, ns, key, options);
}

Expand Down
2 changes: 1 addition & 1 deletion src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function transformOptions(options) {
if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];

// extend supportedLngs with cimode
if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
if (options.supportedLngs?.indexOf?.('cimode') < 0) {
options.supportedLngs = options.supportedLngs.concat(['cimode']);
}

Expand Down
16 changes: 7 additions & 9 deletions src/i18next.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ class I18n extends EventEmitter {
if (typeof language === 'function') usedCallback = language;

if (!this.options.resources || this.options.partialBundledLanguages) {
if (usedLng && usedLng.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); // avoid loading resources for cimode
if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); // avoid loading resources for cimode

const toLoad = [];

Expand All @@ -242,9 +242,7 @@ class I18n extends EventEmitter {
append(usedLng);
}

if (this.options.preload) {
this.options.preload.forEach(l => append(l));
}
this.options.preload?.forEach?.(l => append(l));

this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
Expand Down Expand Up @@ -355,7 +353,7 @@ class I18n extends EventEmitter {
}
if (!this.translator.language) this.translator.changeLanguage(l);

if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);
this.services.languageDetector?.cacheUserLanguage?.(l);
}

this.loadResources(l, err => {
Expand Down Expand Up @@ -412,11 +410,11 @@ class I18n extends EventEmitter {
}

t(...args) {
return this.translator && this.translator.translate(...args);
return this.translator?.translate(...args);
}

exists(...args) {
return this.translator && this.translator.exists(...args);
return this.translator?.exists(...args);
}

setDefaultNamespace(ns) {
Expand Down Expand Up @@ -507,7 +505,7 @@ class I18n extends EventEmitter {
}

dir(lng) {
if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
if (!lng) return 'rtl';

const rtlLngs = [
Expand Down Expand Up @@ -575,7 +573,7 @@ class I18n extends EventEmitter {
'ckb'
];

const languageUtils = (this.services && this.services.languageUtils) || new LanguageUtils(getDefaults()) // for uninitialized usage
const languageUtils = this.services?.languageUtils || new LanguageUtils(getDefaults()) // for uninitialized usage

return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1
? 'rtl'
Expand Down
2 changes: 1 addition & 1 deletion src/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const consoleLogger = {

output(type, args) {
/* eslint no-console: 0 */
if (console && console[type]) console[type].apply(console, args);
console?.[type]?.apply?.(console, args);
},
};

Expand Down
3 changes: 1 addition & 2 deletions src/postProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ export default {

handle(processors, value, key, options, translator) {
processors.forEach((processor) => {
if (this.processors[processor])
value = this.processors[processor].process(value, key, options, translator);
value = this.processors[processor]?.process(value, key, options, translator) ?? value;
});

return value;
Expand Down
4 changes: 2 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function setPath(object, path, newValue) {
e = `${p[p.length - 1]}.${e}`;
p = p.slice(0, p.length - 1);
last = getLastOfPath(object, p, Object);
if (last && last.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
last.obj = undefined;
}
}
Expand Down Expand Up @@ -251,6 +251,6 @@ export function deepFind(obj, path, keySeparator = '.') {
}

export function getCleanedCode(code) {
if (code && code.indexOf('_') > 0) return code.replace('_', '-');
if (code?.indexOf('_') > 0) return code.replace('_', '-');
return code;
}

0 comments on commit 00ff5d5

Please sign in to comment.