import { IColumn } from "../interfaces/IColumn" ; import { IRow } from "../interfaces/IRow" ; import { ICell } from "../interfaces/ICell" ; import * as _ from "lodash" ; import { SortDirection } from "../enums/SortDirection" ; import { ISortService } from "../interfaces/ISortService" ; export class SortService implements ISortService { private columnToSort : IColumn ; private isEnabled : boolean ; private direction : SortDirection ; constructor ( ) { this . direction = SortDirection . Ascending ; } setColumnToSort ( column ) { if ( ! column ) { return ; } this . calculateSortDirection ( column ) ; this . columnToSort = column ; } transformRows ( rows ) { if ( this . isSortingEnabled ( ) == false || this . isSortingNeeded ( ) == false ) { return rows ; } let res ; res = this . applySortOnColumn ( rows ) ; res = this . applySortDirection ( res ) ; return res ; } isSortingNeeded ( ) { return this . columnToSort != undefined ; } isSortingEnabled ( ) { return this . isEnabled ; } setSortingEnabled ( isEnabled ) { this . isEnabled = isEnabled ? true : false ; } isSortedAscending ( ) { return this . direction == SortDirection . Ascending ; } isSortedDescending ( ) { return this . direction == SortDirection . Descending ; } isSortedByColumn ( column ) { return this . columnToSort && column && this . columnToSort . dataKey == column . dataKey ; } private applySortOnColumn ( rows ) { let res = _ . sortBy ( rows , ( aRow ) => { let index = _ . findIndex ( aRow . value , ( cell ) => { return cell . dataKey == this . columnToSort . dataKey ; } ) ; return aRow . value [ index ] . value ; } ) ; return res ; } private calculateSortDirection ( column ) { if ( ! this . columnToSort ) { this . direction = SortDirection . Ascending ; return ; } if ( column . dataKey != this . columnToSort . dataKey ) { this . direction = SortDirection . Ascending ; } else { this . direction = this . direction == SortDirection . Ascending ? SortDirection . Descending : SortDirection . Ascending ; } } private applySortDirection ( res ) { if ( this . direction == SortDirection . Descending ) { res = _ . reverse ( res ) ; } return res ; } }