29 lines
707 B
TypeScript
29 lines
707 B
TypeScript
import { Pipe, PipeTransform } from '@angular/core';
|
|
|
|
@Pipe({ name: 'ipSort' })
|
|
export class IPSort implements PipeTransform {
|
|
transform(array: any[], field: string): any[] {
|
|
array.sort((a: any, b: any) => {
|
|
a = this.ip2num(a[field]);
|
|
b = this.ip2num(b[field]);
|
|
if (a < b) {
|
|
return -1;
|
|
} else if (a > b) {
|
|
return 1;
|
|
} else {
|
|
return 0;
|
|
}
|
|
});
|
|
return array;
|
|
}
|
|
|
|
ip2num(ip: string): number {
|
|
return ip.split('.').map((octet, index, array) => {
|
|
// tslint:disable-next-line:radix
|
|
return parseInt(octet) * Math.pow(256, (array.length - index - 1));
|
|
}).reduce((prev, curr) => {
|
|
return prev + curr;
|
|
});
|
|
}
|
|
}
|