app/@overflow/commons/ui/pipe/ip-sort.ts

29 lines
707 B
TypeScript
Raw Normal View History

2018-09-13 05:47:22 +00:00
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;
});
}
}