// Angular imports // import { PipeTransform, Pipe } from '@angular/core'; import * as _ from 'underscore'; /** * @ngdoc orderByObject * @name fasit.filter.#orderByObject * @ orderByObject * * @description * orderByObject är en smartare orderBy. Kaxigt eller hur? * Inspirerad av http://justinklemm.com/angularjs-filter-ordering-objects-ngrepeat/ */ @Pipe({ name: 'orderByObject' }) export class OrderByObjectPipe implements PipeTransform { transform(items: any[], field?: string, reverse: boolean = false, lowercase: boolean = false): any[] { function getPropValue(propString: string, option: Object): any { const functionParanthesesIndex: number = 2; const properties: string[] = propString.split('.'); let value: any = option; for (let prop of properties) { if (_.isUndefined(value)) { return undefined; } const isFunc: boolean = prop.length > functionParanthesesIndex && prop.substr(prop.length - functionParanthesesIndex, functionParanthesesIndex) === '()'; if (isFunc) { prop = prop.substr(0, prop.length - functionParanthesesIndex); } value = value[prop]; if (isFunc && value) { value = value(); } } if (lowercase) { value = value.toLowerCase(); } return value; } if (!field) { return items; } const filtered: any[] = []; _.forEach(items, item => filtered.push(item)); let sortingProperties: string[] = field.split(' '); const sortingPropertiesReverse: boolean[] = _.map(sortingProperties, (prop: string) => prop.indexOf(':reverse') !== -1); sortingProperties = _.map(sortingProperties, (prop: string) => prop.replace(':reverse', '')); filtered.sort((a, b) => { const aVals: string[] = []; const bVals: string[] = []; let localReverse: boolean = reverse; _.forEach(sortingProperties, sortingProperty => { aVals.push(getPropValue(sortingProperty, a)); bVals.push(getPropValue(sortingProperty, b)); }); for (let i: number = 0; i < sortingProperties.length; ++i) { if (aVals[i] === bVals[i]) { continue; } if (typeof aVals[i] === 'string') { aVals[i] = aVals[i].toLocaleLowerCase(); } if (typeof bVals[i] === 'string') { bVals[i] = bVals[i].toLocaleLowerCase(); } if (sortingPropertiesReverse[i]) { localReverse = !localReverse; } if (localReverse) { return (aVals[i] < bVals[i] || _.isUndefined(aVals[i]) || _.isNull(aVals[i])) ? 1 : -1 ; } else { return (aVals[i] > bVals[i] || _.isUndefined(bVals[i]) || _.isNull(bVals[i])) ? 1 : -1; } } return 0; }); return filtered; } }