mirror of https://github.com/abpframework/abp.git
4 changed files with 43 additions and 21 deletions
@ -1,29 +1,27 @@ |
|||
import { Pipe, PipeTransform, Injectable } from '@angular/core'; |
|||
import clone from 'just-clone'; |
|||
|
|||
import { Injectable, Pipe, PipeTransform } from '@angular/core'; |
|||
export type SortOrder = 'asc' | 'desc'; |
|||
|
|||
@Injectable() |
|||
@Pipe({ |
|||
name: 'abpSort', |
|||
}) |
|||
export class SortPipe implements PipeTransform { |
|||
intialValue: any[]; |
|||
|
|||
transform(value: any[], sortOrder: SortOrder | string = 'asc', sortKey?: string): any { |
|||
sortOrder = sortOrder && (sortOrder.toLowerCase() as any); |
|||
|
|||
if (!this.intialValue) this.intialValue = clone(value); |
|||
|
|||
if (!value || (sortOrder !== 'asc' && sortOrder !== 'desc')) return this.intialValue; |
|||
|
|||
if (!value || (sortOrder !== 'asc' && sortOrder !== 'desc')) return value; |
|||
let sorted; |
|||
if (!sortKey) { |
|||
sorted = value.sort(); |
|||
const numberArray = []; |
|||
const stringArray = []; |
|||
value.forEach(item => (typeof item === 'number' ? numberArray.push(item) : stringArray.push(item))); |
|||
sorted = numberArray.sort().concat(stringArray.sort()); |
|||
} else { |
|||
sorted = value.sort((a, b) => (a[sortKey] < b[sortKey] ? -1 : a[sortKey] > b[sortKey] ? 1 : 0)); |
|||
sorted = value.sort((a, b) => { |
|||
return ( |
|||
Number(typeof b[sortKey] === 'number') - Number(typeof a[sortKey] === 'number') || |
|||
(a[sortKey] < b[sortKey] ? -1 : 1) |
|||
); |
|||
}); |
|||
} |
|||
|
|||
return sortOrder === 'asc' ? sorted : sorted.reverse(); |
|||
} |
|||
} |
|||
|
|||
@ -0,0 +1,30 @@ |
|||
import { createServiceFactory, SpectatorService } from '@ngneat/spectator'; |
|||
import { SortPipe } from '../pipes/sort.pipe'; |
|||
|
|||
describe('SortPipe', () => { |
|||
let pipe: SortPipe; |
|||
let spectator: SpectatorService<SortPipe>; |
|||
const createService = createServiceFactory(SortPipe); |
|||
|
|||
beforeEach(() => { |
|||
spectator = createService(); |
|||
pipe = spectator.service; |
|||
}); |
|||
|
|||
test('should sort array in ascending and descending orders', () => { |
|||
expect(pipe.transform([5, 'b', 1, 'a'], 'asc')).toEqual([1, 5, 'a', 'b']); |
|||
expect(pipe.transform([5, 'b', 1, 'a'], 'desc')).toEqual(['b', 'a', 5, 1]); |
|||
}); |
|||
|
|||
test('should sort object array in given order with given key', () => { |
|||
const array = [{ key: 5 }, { key: 'b' }, { key: 1 }, { key: 'a' }]; |
|||
|
|||
expect(pipe.transform(array, 'asc', 'key')).toEqual([{ key: 1 }, { key: 5 }, { key: 'a' }, { key: 'b' }]); |
|||
expect(pipe.transform(array, 'desc', 'key')).toEqual([{ key: 'b' }, { key: 'a' }, { key: 5 }, { key: 1 }]); |
|||
}); |
|||
|
|||
test('should require an array as value', () => { |
|||
expect(pipe.transform(null, 'asc')).toBeFalsy(); |
|||
expect(pipe.transform(undefined, 'desc')).toBeFalsy(); |
|||
}); |
|||
}); |
|||
Loading…
Reference in new issue