aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/index.ts3
-rw-r--r--src/lib/data.ts30
-rw-r--r--tests/simple.test.ts2
3 files changed, 33 insertions, 2 deletions
diff --git a/src/index.ts b/src/index.ts
index d076567..ad6ef9e 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -8,7 +8,7 @@ import {
} from './lib/locate';
import { show, head, tail } from './lib/display';
import { getSize, info } from './lib/info';
-import { flatten, fromJSON, fromCSV, searchValue } from './lib/data';
+import { flatten, fromJSON, fromCSV, searchValue, sort } from './lib/data';
import { toJSON, toCSV } from './lib/export';
import { isArrayOfType, range, flattenJSON } from './helpers/arrayFunctions';
@@ -84,6 +84,7 @@ class Izuku {
public title = title;
public toJSON = toJSON;
public toCSV = toCSV;
+ public sort = sort;
}
class Frame extends Izuku {
diff --git a/src/lib/data.ts b/src/lib/data.ts
index 6a2fe34..e3c1b7d 100644
--- a/src/lib/data.ts
+++ b/src/lib/data.ts
@@ -193,3 +193,33 @@ export function searchValue(
throw new Error('Invalid options');
}
}
+
+/**
+ * sort - sorts the rowdata based on the column index
+ * @param column: the column index or column name to be sorted
+ * @param order: the order of the sort
+ * @returns the sorted rowdata
+ */
+export function sort(
+ this: Frame,
+ column: number | string,
+ ord?: 'accending' | 'descending'
+) {
+ const order = ord ? ord : 'ascending';
+ const colums = this.columns;
+ const rowdata = this.rowdata;
+ const columnIndex =
+ typeof column === 'number' ? column : colums.indexOf(column);
+ if (columnIndex === -1) {
+ throw new Error('Invalid column index');
+ }
+ const sorted = rowdata.sort((a: any, b: any) => {
+ if (order === 'ascending') {
+ return a[columnIndex] > b[columnIndex] ? 1 : -1;
+ } else {
+ return a[columnIndex] > b[columnIndex] ? -1 : 1;
+ }
+ });
+ this.rowdata = sorted;
+ return this;
+}
diff --git a/tests/simple.test.ts b/tests/simple.test.ts
index 744be1c..24e0126 100644
--- a/tests/simple.test.ts
+++ b/tests/simple.test.ts
@@ -5,6 +5,6 @@ const frame = new Frame(data, header);
describe('Print a frame', () => {
it('should print a frame', () => {
- frame.title('Simple Frame').toCSV(undefined, 'hello');
+ frame.title('Simple Frame').sort(3).show();
});
});