diff options
| author | Bobby <[email protected]> | 2022-01-28 17:06:57 -0500 |
|---|---|---|
| committer | Bobby <[email protected]> | 2022-01-28 17:06:57 -0500 |
| commit | 3e84c49170fc99a692ce8874d7f1545747919986 (patch) | |
| tree | e228577000b04fa582ed03c872ff4cefa59ba6e1 | |
| parent | 5aeab5e6a0e71c6a3e8ddfb02c481dac731148de (diff) | |
| download | izuku.js-3e84c49170fc99a692ce8874d7f1545747919986.tar.xz izuku.js-3e84c49170fc99a692ce8874d7f1545747919986.zip | |
feat: sort by column function
| -rw-r--r-- | src/index.ts | 3 | ||||
| -rw-r--r-- | src/lib/data.ts | 30 | ||||
| -rw-r--r-- | tests/simple.test.ts | 2 |
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(); }); }); |
