Skip to content

Commit ee77f16

Browse files
committed
Smaller refactors to make code more readable
1 parent 772cbd0 commit ee77f16

File tree

5 files changed

+75
-71
lines changed

5 files changed

+75
-71
lines changed

projects/ngx-translate/src/lib/translate.directive.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
Translation,
1010
InterpolationParameters
1111
} from "./translate.service";
12-
import {equals, isDefined} from './util';
12+
import {equals, isDefinedAndNotNull} from './util';
1313

1414
interface ExtendedNode extends Text {
1515
originalContent: string;
@@ -94,7 +94,7 @@ export class TranslateDirective implements AfterViewChecked, OnDestroy {
9494
if (forceUpdate) {
9595
node.lastKey = null;
9696
}
97-
if(isDefined(node.lookupKey)) {
97+
if(isDefinedAndNotNull(node.lookupKey)) {
9898
key = node.lookupKey;
9999
} else if (this.key) {
100100
key = this.key;
@@ -134,13 +134,13 @@ export class TranslateDirective implements AfterViewChecked, OnDestroy {
134134
if (!node.originalContent) {
135135
node.originalContent = this.getContent(node);
136136
}
137-
node.currentValue = isDefined(res) ? res : (node.originalContent || key);
137+
node.currentValue = isDefinedAndNotNull(res) ? res : (node.originalContent || key);
138138
// we replace in the original content to preserve spaces that we might have trimmed
139139
this.setContent(node, this.key ? node.currentValue : node.originalContent.replace(key, node.currentValue));
140140
this._ref.markForCheck();
141141
};
142142

143-
if (isDefined(translations)) {
143+
if (isDefinedAndNotNull(translations)) {
144144
const res = this.translateService.getParsedResult(key, this.currentParams);
145145
if (isObservable(res)) {
146146
res.subscribe({next: onTranslation});
@@ -154,11 +154,11 @@ export class TranslateDirective implements AfterViewChecked, OnDestroy {
154154
}
155155

156156
getContent(node: ExtendedNode): string {
157-
return (isDefined(node.textContent) ? node.textContent : node.data) as string;
157+
return (isDefinedAndNotNull(node.textContent) ? node.textContent : node.data) as string;
158158
}
159159

160160
setContent(node: ExtendedNode, content: string): void {
161-
if (isDefined(node.textContent)) {
161+
if (isDefinedAndNotNull(node.textContent)) {
162162
node.textContent = content;
163163
} else {
164164
node.data = content;

projects/ngx-translate/src/lib/translate.pipe.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
Translation,
99
InterpolationParameters
1010
} from "./translate.service";
11-
import {equals, isDefined, isDict, isString} from "./util";
11+
import {equals, isDefinedAndNotNull, isDict, isString} from "./util";
1212

1313
@Injectable()
1414
@Pipe({
@@ -56,7 +56,7 @@ export class TranslatePipe implements PipeTransform, OnDestroy {
5656
}
5757

5858
let interpolateParams: object | undefined = undefined;
59-
if (isDefined(args[0]) && args.length) {
59+
if (isDefinedAndNotNull(args[0]) && args.length) {
6060
if (isString(args[0]) && args[0].length) {
6161
// we accept objects written in the template such as {n:1}, {'n':1}, {n:'v'}
6262
// which is why we might need to change it to real JSON objects such as {"n":1} or {"n":"v"}

projects/ngx-translate/src/lib/translate.service.ts

Lines changed: 64 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import {Inject, Injectable, InjectionToken} from "@angular/core";
22
import {concat, forkJoin, isObservable, Observable, of, defer} from "rxjs";
33
import {concatMap, map, shareReplay, switchMap, take} from "rxjs/operators";
4-
import {MissingTranslationHandler, MissingTranslationHandlerParams} from "./missing-translation-handler";
4+
import {MissingTranslationHandler} from "./missing-translation-handler";
55
import {TranslateCompiler} from "./translate.compiler";
66
import {TranslateLoader} from "./translate.loader";
77
import {InterpolateFunction, TranslateParser} from "./translate.parser";
88
import {TranslateStore} from "./translate.store";
9-
import {isDefined, isArray, isString, isDict, insertValue} from "./util";
9+
import {isDefinedAndNotNull, isArray, isString, isDict, insertValue} from "./util";
1010

1111
export const ISOLATE_TRANSLATE_SERVICE = new InjectionToken<string>('ISOLATE_TRANSLATE_SERVICE');
1212
export const USE_DEFAULT_LANG = new InjectionToken<string>('USE_DEFAULT_LANG');
@@ -189,7 +189,7 @@ export class TranslateService {
189189
// on init set the defaultLang immediately, but do not emit a change yet
190190
this.store.setDefaultLang(lang, false);
191191
}
192-
192+
193193
const pending = this.loadOrExtendLanguage(lang);
194194
if (isObservable(pending))
195195
{
@@ -331,21 +331,17 @@ export class TranslateService {
331331
{
332332
const textToInterpolate = this.getTextToInterpolate(key);
333333

334-
let res: Translation | undefined;
335-
336-
if (textToInterpolate !== undefined)
334+
if (isDefinedAndNotNull(textToInterpolate))
337335
{
338-
res = this.runInterpolation(textToInterpolate, interpolateParams);
339-
}
340-
else
341-
{
342-
const params: MissingTranslationHandlerParams = {key, translateService: this};
343-
if (typeof interpolateParams !== 'undefined') {
344-
params.interpolateParams = interpolateParams;
345-
}
346-
res = this.missingTranslationHandler.handle(params);
336+
return this.runInterpolation(textToInterpolate, interpolateParams);
347337
}
348338

339+
const res = this.missingTranslationHandler.handle({
340+
key,
341+
translateService: this,
342+
...(interpolateParams !== undefined && { interpolateParams })
343+
});
344+
349345
return res !== undefined ? res : key;
350346
}
351347

@@ -358,66 +354,81 @@ export class TranslateService {
358354
{
359355
if(isArray(translations))
360356
{
361-
return (translations as Translation[]).map((translation) => this.runInterpolation(translation, interpolateParams));
357+
return this.runInterpolationOnArray(translations, interpolateParams);
362358
}
363359
else if (isDict(translations))
364360
{
365-
const result: TranslationObject = {};
366-
for (const key in translations) {
367-
const res = this.runInterpolation(translations[key], interpolateParams);
368-
if(res !== undefined)
369-
{
370-
result[key] = res;
371-
}
372-
}
373-
return result;
361+
return this.runInterpolationOnDict(translations, interpolateParams);
374362
}
375363
else
376364
{
377365
return this.parser.interpolate(translations, interpolateParams);
378366
}
379367
}
380368

369+
private runInterpolationOnArray(translations: InterpolatableTranslation, interpolateParams: InterpolationParameters | undefined)
370+
{
371+
return (translations as Translation[]).map((translation) => this.runInterpolation(translation, interpolateParams));
372+
}
373+
374+
private runInterpolationOnDict(translations: InterpolatableTranslation, interpolateParams: InterpolationParameters | undefined)
375+
{
376+
const result: TranslationObject = {};
377+
for (const key in translations)
378+
{
379+
const res = this.runInterpolation(translations[key], interpolateParams);
380+
if (res !== undefined)
381+
{
382+
result[key] = res;
383+
}
384+
}
385+
return result;
386+
}
387+
381388
/**
382389
* Returns the parsed result of the translations
383390
*/
384-
public getParsedResult(key: string | string[], interpolateParams?: InterpolationParameters): Translation|TranslationObject|Observable<Translation|TranslationObject> {
385-
386-
// handle a bunch of keys
387-
if (key instanceof Array) {
388-
const result: Record<string, Translation|Observable<Translation>> = {};
391+
public getParsedResult(key: string | string[], interpolateParams?: InterpolationParameters): Translation|TranslationObject|Observable<Translation|TranslationObject>
392+
{
393+
return (key instanceof Array) ? this.getParsedResultForArray(key, interpolateParams) : this.getParsedResultForKey(key, interpolateParams);
394+
}
389395

390-
let observables = false;
391-
for (const k of key) {
392-
result[k] = this.getParsedResultForKey(k, interpolateParams);
393-
observables = observables || isObservable(result[k]);
394-
}
396+
private getParsedResultForArray(key: string[], interpolateParams: InterpolationParameters | undefined)
397+
{
398+
const result: Record<string, Translation | Observable<Translation>> = {};
395399

396-
if (!observables) {
397-
return result as TranslationObject;
398-
}
400+
let observables = false;
401+
for (const k of key)
402+
{
403+
result[k] = this.getParsedResultForKey(k, interpolateParams);
404+
observables = observables || isObservable(result[k]);
405+
}
399406

400-
const sources: Observable<Translation>[] = key.map(k => makeObservable(result[k]));
401-
return forkJoin(sources).pipe(
402-
map((arr: (Translation)[]) => {
403-
const obj: TranslationObject = {};
404-
arr.forEach((value:Translation, index: number) => {
405-
obj[key[index]] = value;
406-
});
407-
return obj;
408-
})
409-
);
407+
if (!observables)
408+
{
409+
return result as TranslationObject;
410410
}
411411

412-
return this.getParsedResultForKey(key, interpolateParams);
412+
const sources: Observable<Translation>[] = key.map(k => makeObservable(result[k]));
413+
return forkJoin(sources).pipe(
414+
map((arr: (Translation)[]) =>
415+
{
416+
const obj: TranslationObject = {};
417+
arr.forEach((value: Translation, index: number) =>
418+
{
419+
obj[key[index]] = value;
420+
});
421+
return obj;
422+
})
423+
);
413424
}
414425

415426
/**
416427
* Gets the translated value of a key (or an array of keys)
417428
* @returns the translated key, or an object of translated keys
418429
*/
419430
public get(key: string | string[], interpolateParams?: InterpolationParameters): Observable<Translation|TranslationObject> {
420-
if (!isDefined(key) || !key.length) {
431+
if (!isDefinedAndNotNull(key) || !key.length) {
421432
throw new Error(`Parameter "key" is required and cannot be empty`);
422433
}
423434
// check if we are loading a new translation to use
@@ -438,7 +449,7 @@ export class TranslateService {
438449
* @returns A stream of the translated key, or an object of translated keys
439450
*/
440451
public getStreamOnTranslationChange(key: string | string[], interpolateParams?: InterpolationParameters): Observable<Translation|TranslationObject> {
441-
if (!isDefined(key) || !key.length) {
452+
if (!isDefinedAndNotNull(key) || !key.length) {
442453
throw new Error(`Parameter "key" is required and cannot be empty`);
443454
}
444455

@@ -459,7 +470,7 @@ export class TranslateService {
459470
* @returns A stream of the translated key, or an object of translated keys
460471
*/
461472
public stream(key: string | string[], interpolateParams?: InterpolationParameters): Observable<Translation|TranslationObject> {
462-
if (!isDefined(key) || !key.length) {
473+
if (!isDefinedAndNotNull(key) || !key.length) {
463474
throw new Error(`Parameter "key" required`);
464475
}
465476

@@ -480,7 +491,7 @@ export class TranslateService {
480491
*/
481492
public instant(key: string | string[], interpolateParams?: InterpolationParameters): Translation|TranslationObject
482493
{
483-
if (!isDefined(key) || key.length === 0) {
494+
if (!isDefinedAndNotNull(key) || key.length === 0) {
484495
throw new Error('Parameter "key" is required and cannot be empty');
485496
}
486497

projects/ngx-translate/src/lib/translate.store.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,6 @@ export class TranslateStore
106106
return this._onDefaultLangChange.asObservable();
107107
}
108108

109-
/**
110-
* Update the list of available languages
111-
*/
112-
public updateLanguages(): void {
113-
this.addLanguages(Object.keys(this.translations));
114-
}
115-
116109
public addLanguages(languages: Language[]): void
117110
{
118111
this.languages = Array.from(new Set([...this.languages, ...languages]));

projects/ngx-translate/src/lib/util.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export function equals(o1: any, o2: any): boolean {
5050
return false;
5151
}
5252

53-
export function isDefined(value: any): boolean {
53+
export function isDefinedAndNotNull(value: any): boolean {
5454
return typeof value !== 'undefined' && value !== null;
5555
}
5656

@@ -142,8 +142,8 @@ export function getValue(target: any, key: string): any
142142
{
143143
key += keys.shift();
144144
if (
145-
isDefined(target) &&
146-
(isDefined(target[key]) || target[key] === null) &&
145+
isDefinedAndNotNull(target) &&
146+
(isDefinedAndNotNull(target[key]) || target[key] === null) &&
147147
(isDict(target[key]) || isArray(target[key]) || !keys.length)
148148
)
149149
{

0 commit comments

Comments
 (0)