All files / modules/acute-common/src/pipes order-by.pipe.ts

0% Statements 0/31
0% Branches 0/45
0% Functions 0/4
0% Lines 0/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                                                                                     
import { Pipe, PipeTransform } from '@angular/core';
 
@Pipe({ name: 'acuteOrderBy', pure: false, standalone: true })
export class OrderByPipe implements PipeTransform {
  static _orderByComparator(a: any, b: any): number {
    if (isNaN(parseFloat(a)) || !isFinite(a) || isNaN(parseFloat(b)) || !isFinite(b)) {
      //Isn't a number so lowercase the string to properly compare
      if (String(a).toLowerCase() < String(b).toLowerCase()) return -1;
      if (String(a).toLowerCase() > String(b).toLowerCase()) return 1;
    } else {
      //Parse strings as numbers to compare properly
      if (parseFloat(a) < parseFloat(b)) return -1;
      if (parseFloat(a) > parseFloat(b)) return 1;
    }
 
    return 0; //equal each other
  }
 
  transform(input: any, [config = '+']): any {
    if (!Array.isArray(input)) return input;
 
    if (!Array.isArray(config) || (Array.isArray(config) && config.length == 1)) {
      const propertyToCheck: string = !Array.isArray(config) ? config : config[0];
      const desc = propertyToCheck.substr(0, 1) == '-';
 
      //Basic array
      if (!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+') {
        return !desc ? input.sort() : input.sort().reverse();
      } else {
        const property: string =
          propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-' ? propertyToCheck.substr(1) : propertyToCheck;
 
        return input.sort(function (a: any, b: any) {
          return !desc
            ? OrderByPipe._orderByComparator(a[property], b[property])
            : -OrderByPipe._orderByComparator(a[property], b[property]);
        });
      }
    } else {
      //Loop over property of the array in order and sort
      return input.sort(function (a: any, b: any) {
        for (let i: number = 0; i < config.length; i++) {
          const desc = config[i].substr(0, 1) == '-';
          const property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-' ? config[i].substr(1) : config[i];
 
          const comparison = !desc
            ? OrderByPipe._orderByComparator(a[property], b[property])
            : -OrderByPipe._orderByComparator(a[property], b[property]);
 
          //Don't return 0 yet in case of needing to sort by next property
          if (comparison != 0) return comparison;
        }
 
        return 0; //equal each other
      });
    }
  }
}