grafana/public/app/core/table_model.ts
Martin Packman 6046c8b4ca Make table sorting stable when null values exist (#12362)
Currently if a null appears in a table column, for instance in data
returned by postgres, sorting on that gives an arbitrary order. This
is due to null being neither greater or less than any string, which
makes the sort unstable.

Change the table sort function to compare on nullness first. Note
this is a slight behaviour change for numbers, which would otherwise
treat null and 0 as equivalent.

Signed-off-by: Martin Packman <gzlist@googlemail.com>
2018-07-02 11:14:41 -07:00

45 lines
895 B
TypeScript

export default class TableModel {
columns: any[];
rows: any[];
type: string;
columnMap: any;
constructor() {
this.columns = [];
this.columnMap = {};
this.rows = [];
this.type = 'table';
}
sort(options) {
if (options.col === null || this.columns.length <= options.col) {
return;
}
this.rows.sort(function(a, b) {
a = a[options.col];
b = b[options.col];
// Sort null or undefined seperately from comparable values
return +(a == null) - +(b == null) || +(a > b) || -(a < b);
});
if (options.desc) {
this.rows.reverse();
}
this.columns[options.col].sort = true;
this.columns[options.col].desc = options.desc;
}
addColumn(col) {
if (!this.columnMap[col.text]) {
this.columns.push(col);
this.columnMap[col.text] = col;
}
}
addRow(row) {
this.rows.push(row);
}
}