Skip to content

Commit

Permalink
#8 Refactor achievable skill sort pipe
Browse files Browse the repository at this point in the history
- Made methods private and static.
- Consequently use of null safe variable.
- Decompose logic

Signed-off-by: Sven Strittmatter <[email protected]>
  • Loading branch information
Weltraumschaf committed Jun 1, 2022
1 parent 3d5b2eb commit fe1ab65
Showing 1 changed file with 24 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -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);
});
}
}

0 comments on commit fe1ab65

Please sign in to comment.