From fe1ab6502d2ba737b92d52a095db5bf448fe0737 Mon Sep 17 00:00:00 2001 From: Sven Strittmatter Date: Wed, 1 Jun 2022 13:18:51 +0200 Subject: [PATCH] #8 Refactor achievable skill sort pipe - Made methods private and static. - Consequently use of null safe variable. - Decompose logic Signed-off-by: Sven Strittmatter --- .../shared/pipe/achievable-skill-sort.pipe.ts | 34 +++++++++++++------ 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/src/main/webapp/app/custom/shared/pipe/achievable-skill-sort.pipe.ts b/src/main/webapp/app/custom/shared/pipe/achievable-skill-sort.pipe.ts index 6ccb767c..045b1571 100644 --- a/src/main/webapp/app/custom/shared/pipe/achievable-skill-sort.pipe.ts +++ b/src/main/webapp/app/custom/shared/pipe/achievable-skill-sort.pipe.ts @@ -1,19 +1,33 @@ import { Pipe, PipeTransform } from '@angular/core'; import { IAchievableSkill } from 'app/custom/entities/achievable-skill/achievable-skill.model'; +import { TranslateModelService } from '../translate-model/translate-model.service'; -type sortArg = keyof IAchievableSkill; +type SortableProperties = keyof IAchievableSkill; -@Pipe({ name: 'achievableSkillSort' }) +@Pipe({ + name: 'achievableSkillSort', + pure: false, // Must not be pure so that already rendered components will be rendered again after language switch. +}) export class AchievableSkillSortPipe implements PipeTransform { - transform(skills: IAchievableSkill[], sortProperty: sortArg): IAchievableSkill[] { - const sortPropertyNullSafe = this.defaultString(sortProperty); - const reverse = ['score', 'rateCount'].includes(sortPropertyNullSafe) ? -1 : 1; - return Array.from(skills).sort( - (skill1, skill2) => reverse * this.defaultString(skill1[sortProperty]).localeCompare(this.defaultString(skill2[sortProperty])) - ); + constructor(private translation: TranslateModelService) {} + + private static defaultString(smth: any): string { + return smth || smth === 0 ? String(smth) : ''; + } + + private static shouldSortReverse(propertyName: SortableProperties): boolean { + return ['score', 'rateCount'].includes(propertyName); } - private defaultString(smth: any): string { - return smth || smth === 0 ? String(smth) : String(); + transform(skills: IAchievableSkill[], propertyName: SortableProperties): IAchievableSkill[] { + const nullSafePropertyName = AchievableSkillSortPipe.defaultString(propertyName) as SortableProperties; + const sortOrder = AchievableSkillSortPipe.shouldSortReverse(nullSafePropertyName) ? -1 : 1; + + return Array.from(skills).sort((leftSkill, rightSkill) => { + const leftValue = AchievableSkillSortPipe.defaultString(leftSkill[nullSafePropertyName]); + const rightValue = AchievableSkillSortPipe.defaultString(rightSkill[nullSafePropertyName]); + + return sortOrder * leftValue.localeCompare(rightValue); + }); } }