Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Chore]: Technical: Translate table utils (#1742)

Maksim Suslov7a11260dad20
diff --git a/src/utils/table-utils/data-container-interface.d.ts b/src/utils/table-utils/data-container-interface.ts
similarity index 100%
rename from src/utils/table-utils/data-container-interface.d.ts
rename to src/utils/table-utils/data-container-interface.ts
diff --git a/src/utils/table-utils/data-container-utils.d.ts b/src/utils/table-utils/data-container-utils.d.ts
deleted file mode 100644
index 275646956..000000000
--- a/src/utils/table-utils/data-container-utils.d.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import {Field} from './kepler-table';
-import {DataContainerInterface} from './data-container-interface';
-
-type DataForm = {
- ROWS_ARRAY: string;
-};
-
-export type DataContainerOptions = {
- inputDataFormat?: string; // one of DataForm
- fields?: Field[];
-};
-
-/**
- * Creates a data container wrapper for the data.
- * @param data Data.
- * @param options Options.
- * @returns A data container object which is based on data and options.
- */
-export function createDataContainer(
- data: any[],
- options?: DataContainerOptions
-): DataContainerInterface;
-
-/**
- * Creates a data container wrapper around another data container.
- * @param dataContainer Parent data container.
- * @param indices An array of row indices in the parent data container.
- */
-export function createIndexedDataContainer(
- dataContainer: DataContainerInterface,
- indices: number[]
-): DataContainerInterface;
-
-/**
- * Get a sample of rows from a data container.
- * @param dataContainer Data container to get samples from.
- * @param sampleSize Max number of samples.
- * @returns A data container which contains samples from the original data container.
- */
-export function getSampleData(
- dataContainer: DataContainerInterface,
- sampleSize?: number
-): DataContainerInterface;
\ No newline at end of file
diff --git a/src/utils/table-utils/data-container-utils.js b/src/utils/table-utils/data-container-utils.ts
similarity index 59%
rename from src/utils/table-utils/data-container-utils.js
rename to src/utils/table-utils/data-container-utils.ts
index a19887691..124904523 100644
--- a/src/utils/table-utils/data-container-utils.js
+++ b/src/utils/table-utils/data-container-utils.ts
@@ -21,18 +21,32 @@
import {RowDataContainer} from './row-data-container';
import {IndexedDataContainer} from './indexed-data-container';
-/** @type {import('./data-container-utils').DataForm} */
+import {DataContainerInterface} from './data-container-interface';
+import {Field} from './kepler-table';
+
+export type DataContainerOptions = {
+ inputDataFormat?: string; // one of DataForm
+ fields?: Field[];
+};
+
export const DataForm = {
ROWS_ARRAY: 'ROWS_ARRAY'
};
-/** @type {import('./data-container-utils').DataContainerOptions} */
-const defaultOptions = {
+const defaultOptions: DataContainerOptions = {
inputDataFormat: DataForm.ROWS_ARRAY
};
-/** @type {typeof import('./data-container-utils').createDataContainer} */
-export function createDataContainer(data, options = defaultOptions) {
+/**
+ * Creates a data container wrapper for the data.
+ * @param data Data.
+ * @param options Options.
+ * @returns A data container object which is based on data and options.
+ */
+export function createDataContainer(
+ data: any[],
+ options: DataContainerOptions = defaultOptions
+): DataContainerInterface {
options = {...defaultOptions, ...options};
if (options.inputDataFormat === DataForm.ROWS_ARRAY) {
@@ -42,17 +56,32 @@ export function createDataContainer(data, options = defaultOptions) {
throw Error('Failed to create a data container: not implemented format');
}
-/** @type {typeof import('./data-container-utils').createIndexedDataContainer} */
-export function createIndexedDataContainer(dataContainer, indices) {
+/**
+ * Creates a data container wrapper around another data container.
+ * @param dataContainer Parent data container.
+ * @param indices An array of row indices in the parent data container.
+ */
+export function createIndexedDataContainer(
+ dataContainer: DataContainerInterface,
+ indices: number[]
+): DataContainerInterface {
return new IndexedDataContainer(dataContainer, indices);
}
-/** @type {typeof import('./data-container-utils').getSampleData} */
-export function getSampleData(dataContainer, sampleSize = 500) {
+/**
+ * Get a sample of rows from a data container.
+ * @param dataContainer Data container to get samples from.
+ * @param sampleSize Max number of samples.
+ * @returns A data container which contains samples from the original data container.
+ */
+export function getSampleData(
+ dataContainer: DataContainerInterface,
+ sampleSize = 500
+): DataContainerInterface {
const numberOfRows = dataContainer.numRows();
const sampleStep = Math.max(Math.floor(numberOfRows / sampleSize), 1);
- const indices = [];
+ const indices: number[] = [];
for (let i = 0; i < numberOfRows; i += sampleStep) {
indices.push(i);
}
diff --git a/src/utils/table-utils/data-row.d.ts b/src/utils/table-utils/data-row.jdoc.ts
similarity index 86%
rename from src/utils/table-utils/data-row.d.ts
rename to src/utils/table-utils/data-row.jdoc.ts
index 878336e62..1a715468d 100644
--- a/src/utils/table-utils/data-row.d.ts
+++ b/src/utils/table-utils/data-row.jdoc.ts
@@ -1,3 +1,5 @@
+// TODO: Move JDoc to correct place
+// @ts-nocheck
import {DataContainerInterface} from './data-container-interface';
/**
@@ -25,12 +27,12 @@ export class DataRow {
constructor(dataContainer: DataContainerInterface | null, rowIndex: number);
/**
- * Conditionally creates a DataRow object.
- * @param sharedRowDesc Accepts forllowing options:
- * - true indicates that new DataRow should be created.
- * - falsy value or a DataRow object is passed through without any change.
- * @returns A new DataRow object or unchanged input argument.
- */
+ * Conditionally creates a DataRow object.
+ * @param sharedRowDesc Accepts forllowing options:
+ * - true indicates that new DataRow should be created.
+ * - falsy value or a DataRow object is passed through without any change.
+ * @returns A new DataRow object or unchanged input argument.
+ */
static createSharedRow(sharedRowDesc: SharedRowOptions): SharedRowOptionsResult;
/**
diff --git a/src/utils/table-utils/data-row.js b/src/utils/table-utils/data-row.ts
similarity index 61%
rename from src/utils/table-utils/data-row.js
rename to src/utils/table-utils/data-row.ts
index 51cbd6f5b..24d42eb39 100644
--- a/src/utils/table-utils/data-row.js
+++ b/src/utils/table-utils/data-row.ts
@@ -18,34 +18,44 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+import {DataContainerInterface} from './data-container-interface';
+
+export type SharedRowOptions = DataRow | boolean | undefined;
+export type SharedRowOptionsResult = DataRow | false | undefined;
+
export class DataRow {
- constructor(dataContainer, rowIndex) {
- this.setSource(dataContainer, rowIndex);
+ _dataContainer: DataContainerInterface | null;
+
+ _rowIndex: number;
+
+ constructor(dataContainer: DataContainerInterface | null, rowIndex: number) {
+ this._dataContainer = dataContainer;
+ this._rowIndex = rowIndex;
}
- static createSharedRow(sharedRowDesc) {
+ static createSharedRow(sharedRowDesc: SharedRowOptions): SharedRowOptionsResult {
if (sharedRowDesc === true) {
return new DataRow(null, 0);
}
return sharedRowDesc;
}
- valueAt(columnIndex) {
- return this._dataContainer.valueAt(this._rowIndex, columnIndex);
+ valueAt(columnIndex: number): any {
+ return this._dataContainer?.valueAt(this._rowIndex, columnIndex);
}
- values() {
- return this._dataContainer.rowAsArray(this._rowIndex);
+ values(): any[] {
+ return this._dataContainer ? this._dataContainer.rowAsArray(this._rowIndex) : [];
}
- setSource(dataContainer, rowIndex) {
+ setSource(dataContainer: DataContainerInterface, rowIndex: number): void {
this._dataContainer = dataContainer;
this._rowIndex = rowIndex;
}
- map(handler) {
- const numColumns = this._dataContainer.numColumns();
- const out = [];
+ map(handler: (elem: any, index: number) => any): any[] {
+ const numColumns = this._dataContainer?.numColumns() || 0;
+ const out: any[] = [];
for (let column = 0; column < numColumns; ++column) {
out[column] = handler(this.valueAt(column), column);
}
diff --git a/src/utils/table-utils/index.d.ts b/src/utils/table-utils/index.d.ts
deleted file mode 100644
index 004bb10e7..000000000
--- a/src/utils/table-utils/index.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {createDataContainer, createIndexedDataContainer} from './data-container-utils';
diff --git a/src/utils/table-utils/index.js b/src/utils/table-utils/index.ts
similarity index 100%
rename from src/utils/table-utils/index.js
rename to src/utils/table-utils/index.ts
diff --git a/src/utils/table-utils/indexed-data-container.d.ts b/src/utils/table-utils/indexed-data-container.d.ts
deleted file mode 100644
index 3536fe6c9..000000000
--- a/src/utils/table-utils/indexed-data-container.d.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import {DataContainerInterface} from './data-container-interface';
-import {DataRow, SharedRowOptions} from './data-row';
-
-/**
- * A data container wrapper around another data container.
- * You have to pass an array of indices to reference rows in the parent data container.
- * For example indices [3, 4, 6, 8] means that IndexedDataContainer is going to have
- * 4 rows and row(2) points to 6th row in the referenced data container.
- */
-export class IndexedDataContainer implements DataContainerInterface {
- constructor(parentDataContainer: DataContainerInterface, indices: number[]);
-
- numRows(): number;
- numColumns(): number;
- valueAt(rowIndex: number, columnIndex: number): any;
- row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow;
- rowAsArray(rowIndex: number): any[];
- rows(sharedRow?: SharedRowOptions): Generator<DataRow, void, any>;
- column(columnIndex: number): Generator<any, void, any>;
- flattenData(): any[][];
- getPlainIndex(): number[];
- map(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions, options?: RangeOptions): any[];
- mapIndex(func: ({index: number}, dc: DataContainerInterface) => any, options?: RangeOptions): any[];
- find(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions): DataRow | undefined;
- reduce(func: (acc: any, row: DataRow, index: number) => any, initialValue: any, sharedRow?: SharedRowOptions): any;
-}
diff --git a/src/utils/table-utils/indexed-data-container.js b/src/utils/table-utils/indexed-data-container.ts
similarity index 64%
rename from src/utils/table-utils/indexed-data-container.js
rename to src/utils/table-utils/indexed-data-container.ts
index 6d6668834..cd6632b65 100644
--- a/src/utils/table-utils/indexed-data-container.js
+++ b/src/utils/table-utils/indexed-data-container.ts
@@ -18,15 +18,20 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import {DataRow} from './data-row';
+import {DataContainerInterface, RangeOptions} from './data-container-interface';
+import {DataRow, SharedRowOptions} from './data-row';
/**
- * @param {import('./data-container-interface').DataContainerInterface} dataContainer
- * @param {number[]} indices
- * @param {import('./data-row').SharedRowOptions} sharedRow
- * @returns {Generator<DataRow, void, unknown>}
+ * @param dataContainer
+ * @param indices
+ * @param sharedRow
+ * @returns
*/
-function* rowsIterator(dataContainer, indices, sharedRow) {
+function* rowsIterator(
+ dataContainer: DataContainerInterface,
+ indices: number[],
+ sharedRow: SharedRowOptions
+): Generator<DataRow> {
const numRows = indices.length;
for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
const mappedRowIndex = indices[rowIndex];
@@ -35,12 +40,16 @@ function* rowsIterator(dataContainer, indices, sharedRow) {
}
/**
- * @param {import('./data-container-interface').DataContainerInterface} dataContainer
- * @param {number[]} indices
- * @param {number} columnIndex
- * @returns {Generator<any, void, unknown>}
+ * @param dataContainer
+ * @param indices
+ * @param columnIndex
+ * @returns
*/
-function* columnIterator(dataContainer, indices, columnIndex) {
+function* columnIterator(
+ dataContainer: DataContainerInterface,
+ indices: number[],
+ columnIndex: number
+): Generator<any> {
const numRows = indices.length;
for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
const mappedRowIndex = indices[rowIndex];
@@ -48,54 +57,63 @@ function* columnIterator(dataContainer, indices, columnIndex) {
}
}
-export class IndexedDataContainer {
- constructor(parentDataContainer, indices) {
+/**
+ * A data container wrapper around another data container.
+ * You have to pass an array of indices to reference rows in the parent data container.
+ * For example indices [3, 4, 6, 8] means that IndexedDataContainer is going to have
+ * 4 rows and row(2) points to 6th row in the referenced data container.
+ */
+export class IndexedDataContainer implements DataContainerInterface {
+ _parentDataContainer: DataContainerInterface;
+ _indices: number[];
+
+ constructor(parentDataContainer: DataContainerInterface, indices: number[]) {
this._parentDataContainer = parentDataContainer;
this._indices = indices;
}
- numRows() {
+ numRows(): number {
return this._indices.length;
}
- numColumns() {
+ numColumns(): number {
return this._parentDataContainer.numColumns();
}
/**
* Remaps a local index to an index in the parent dataset
- * @param {number} rowIndex
+ * @param rowIndex
* @returns number
*/
- _mappedRowIndex(rowIndex) {
+ _mappedRowIndex(rowIndex: number): number {
return this._indices[rowIndex];
}
- valueAt(rowIndex, columnIndex) {
+ valueAt(rowIndex: number, columnIndex: number): any {
return this._parentDataContainer.valueAt(this._mappedRowIndex(rowIndex), columnIndex);
}
- row(rowIndex, sharedRow) {
+ row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow {
return this._parentDataContainer.row(this._mappedRowIndex(rowIndex), sharedRow);
}
- rowAsArray(rowIndex) {
+ rowAsArray(rowIndex: number): any[] {
return this._parentDataContainer.rowAsArray(this._mappedRowIndex(rowIndex));
}
- rows(sharedRow) {
+ rows(sharedRow?: SharedRowOptions) {
return rowsIterator(this._parentDataContainer, this._indices, sharedRow);
}
- column(columnIndex) {
+ column(columnIndex: number) {
return columnIterator(this._parentDataContainer, this._indices, columnIndex);
}
- getPlainIndex() {
+ getPlainIndex(): number[] {
return this._indices.map((_, i) => i);
}
- flattenData() {
+ flattenData(): any[][] {
const tSharedRow = DataRow.createSharedRow(true);
return this._indices.map((_, i) => {
@@ -103,13 +121,17 @@ export class IndexedDataContainer {
}, this);
}
- map(func, sharedRow, options = {}) {
+ map<T>(
+ func: (row: DataRow, index: number) => T,
+ sharedRow?: SharedRowOptions,
+ options: RangeOptions = {}
+ ): T[] {
const {start = 0, end = this.numRows()} = options;
const endRow = Math.min(this.numRows(), end);
const tSharedRow = DataRow.createSharedRow(sharedRow);
- const out = [];
+ const out: T[] = [];
for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
const row = this.row(rowIndex, tSharedRow);
out.push(func(row, rowIndex));
@@ -117,18 +139,24 @@ export class IndexedDataContainer {
return out;
}
- mapIndex(func, options = {}) {
+ mapIndex<T>(
+ func: ({index: number}, dc: DataContainerInterface) => T,
+ options: RangeOptions = {}
+ ): T[] {
const {start = 0, end = this.numRows()} = options;
const endRow = Math.min(this.numRows(), end);
- const out = [];
+ const out: T[] = [];
for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
out.push(func({index: this._mappedRowIndex(rowIndex)}, this._parentDataContainer));
}
return out;
}
- find(func, sharedRow) {
+ find(
+ func: (row: DataRow, index: number) => boolean,
+ sharedRow?: SharedRowOptions
+ ): DataRow | undefined {
const tSharedRow = DataRow.createSharedRow(sharedRow);
for (let rowIndex = 0; rowIndex < this.numRows(); ++rowIndex) {
@@ -140,7 +168,11 @@ export class IndexedDataContainer {
return undefined;
}
- reduce(func, initialValue, sharedRow) {
+ reduce<T>(
+ func: (acc: T, row: DataRow, index: number) => T,
+ initialValue: T,
+ sharedRow?: SharedRowOptions
+ ): T {
const tSharedRow = DataRow.createSharedRow(sharedRow);
for (let rowIndex = 0; rowIndex < this._indices.length; ++rowIndex) {
diff --git a/src/utils/table-utils/kepler-table.d.ts b/src/utils/table-utils/kepler-table.d.ts
deleted file mode 100644
index f88286780..000000000
--- a/src/utils/table-utils/kepler-table.d.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import {RGBColor} from '../../reducers/types';
-import {Layer} from 'layers';
-import {Filter} from '../reducers/vis-state-updaters';
-import {Dataset} from '../../reducers/vis-state-updaters';
-import {DataContainerInterface} from './data-container-interface';
-
-export type Field = {
- analyzerType: string;
- id?: string;
- name: string;
- displayName: string;
- format: string;
- type: string;
- fieldIdx: number;
- valueAccessor(v: {index: number}): any;
- filterProps?: any;
- metadata?: any;
- displayName: string;
-};
-
-export type GpuFilter = {
- filterRange: number[][];
- filterValueUpdateTriggers: any;
- filterValueAccessor: (
- dc: DataContainerInterface
- ) => (
- getIndex?: (any) => number,
- getData?: (dc: DataContainerInterface, d: any, fieldIndex: number) => any
- ) => (d: any) => number;
-};
-
-export type FieldPair = {
- defaultName: string;
- pair: {
- [key: string]: {
- fieldIdx: number;
- value: string;
- };
- };
- suffix: string[];
-};
-
-export type FilterRecord = {
- dynamicDomain: Filter[];
- fixedDomain: Filter[];
- cpu: Filter[];
- gpu: Filter[];
-};
-
-export type FilterDatasetOpt = {
- // only allow cpu filtering
- cpuOnly?: boolean;
- // ignore filter for domain calculation
- ignoreDomain?: boolean;
-};
-
-export function sortDatasetByColumn(dataset: KeplerTable, column: string, mode?: string): Dataset;
-
-export function findPointFieldPairs(fields: Field[]): FieldPair[];
-
-export class KeplerTable {
- readonly id: string;
-
- constructor(schema: {
- info?: ProtoDataset['info'];
- data: ProtoDataset['data'];
- color: RGBColor;
- metadata?: ProtoDataset['metadata'];
- supportedFilterTypes?: ProtoDataset['supportedFilterTypes'];
- });
- type?: string;
- label: string;
- color: RGBColor;
-
- // fields and data
- fields: Field[];
-
- dataContainer: DataContainerInterface;
-
- allIndexes: number[];
- filteredIndex: number[];
- filteredIdxCPU?: number[];
- filteredIndexForDomain: number[];
- fieldPairs: FieldPair[];
- gpuFilter: GpuFilter;
- filterRecord?: FilterRecord;
- filterRecordCPU?: FilterRecord;
- changedFilters?: any;
-
- // table-injected metadata
- sortColumn?: {
- // column name: sorted idx
- [key: string]: string; // ASCENDING | DESCENDING | UNSORT
- };
- sortOrder?: number[] | null;
-
- pinnedColumns?: string[];
- supportedFilterTypes: string[] | undefined;
- // table-injected metadata
- metadata: object;
-
- // methods
- getColumnField(columnName: string): Field | undefined;
- getColumnFieldIdx(columnName: string): number;
- getColumnFilterDomain(field: Field): FieldDomain;
- getColumnLayerDomain(field: Field, scaleType: string): number[] | string[] | [number, number];
- getValue(columnName: string, rowIdx: number): any;
- updateColumnField(fieldIdx: number, newField: Field): void;
- updateTableColor(newColor: RGBColor): void;
- getColumnFilterProps(fieldName: string): Field['filterProps'] | null | undefined;
- filterTable(filters: Filter[], layers: Layer[], opt?: FilterDatasetOpt): KeplerTable;
- filterTableCPU(filters: Filter[], layers: Layer[]): KeplerTable;
-
- // private methods
- _assetField(fieldName: string, condition: any): void;
-}
-
-export function copyTable<T extends {}>(original: T): T;
-export function copyTableAndUpdate<T extends {}>(original: T, options: Partial<T>): T;
-export function getFieldValueAccessor<
- F extends {
- type: Field['type'];
- format: Field['format'];
- }
->(f: F, i: number): FieldValueAccessor;
-export function pinTableColumns(dataset: KeplerTable, column: string): KeplerTable;
-export default KeplerTable;
diff --git a/src/utils/table-utils/kepler-table.js b/src/utils/table-utils/kepler-table.ts
similarity index 78%
rename from src/utils/table-utils/kepler-table.js
rename to src/utils/table-utils/kepler-table.ts
index 2d3641115..c6532df3e 100644
--- a/src/utils/table-utils/kepler-table.js
+++ b/src/utils/table-utils/kepler-table.ts
@@ -32,7 +32,8 @@ import {
getFilterFunction,
filterDataByFilterTypes,
getNumericFieldDomain,
- getTimestampFieldDomain
+ getTimestampFieldDomain,
+ FilterResult
} from 'utils/filter-utils';
import {maybeToDate, getSortingFunction} from 'utils/data-utils';
import {
@@ -46,22 +47,118 @@ import {ALL_FIELD_TYPES, SCALE_TYPES} from 'constants/default-settings';
import {createDataContainer} from './data-container-utils';
+import {RGBColor} from 'reducers/types';
+import {Layer} from 'layers';
+import {FieldDomain, Filter} from 'reducers/vis-state-updaters';
+import {DataContainerInterface} from './data-container-interface';
+import {ProtoDataset} from 'actions';
+
+export type Field = {
+ analyzerType: string;
+ id?: string;
+ name: string;
+ displayName: string;
+ format: string;
+ type: string;
+ fieldIdx: number;
+ valueAccessor(v: {index: number}): any;
+ filterProps?: any;
+ metadata?: any;
+};
+
+export type GpuFilter = {
+ filterRange: number[][];
+ filterValueUpdateTriggers: any;
+ filterValueAccessor: (
+ dc: DataContainerInterface
+ ) => (
+ getIndex?: (any) => number,
+ getData?: (dc: DataContainerInterface, d: any, fieldIndex: number) => any
+ ) => (d: any) => number;
+};
+
+export type FieldPair = {
+ defaultName: string;
+ pair: {
+ [key: string]: {
+ fieldIdx: number;
+ value: string;
+ };
+ };
+ suffix: string[];
+};
+
+export type FilterRecord = {
+ dynamicDomain: Filter[];
+ fixedDomain: Filter[];
+ cpu: Filter[];
+ gpu: Filter[];
+};
+
+export type FilterDatasetOpt = {
+ // only allow cpu filtering
+ cpuOnly?: boolean;
+ // ignore filter for domain calculation
+ ignoreDomain?: boolean;
+};
+
// Unique identifier of each field
const FID_KEY = 'name';
-/** @typedef {import('./kepler-table').KeplerTable} KeplerTableClass} */
-
-/**
- * @type {KeplerTableClass}
- */
class KeplerTable {
- constructor({info = {}, data, color, metadata, supportedFilterTypes}) {
+ readonly id: string;
+
+ type?: string;
+ label: string;
+ color: RGBColor;
+
+ // fields and data
+ fields: Field[];
+
+ dataContainer: DataContainerInterface;
+
+ allIndexes: number[];
+ filteredIndex: number[];
+ filteredIdxCPU?: number[];
+ filteredIndexForDomain: number[];
+ fieldPairs: FieldPair[];
+ gpuFilter: GpuFilter;
+ filterRecord?: FilterRecord;
+ filterRecordCPU?: FilterRecord;
+ changedFilters?: any;
+
+ // table-injected metadata
+ sortColumn?: {
+ // column name: sorted idx
+ [key: string]: string; // ASCENDING | DESCENDING | UNSORT
+ };
+ sortOrder?: number[] | null;
+
+ pinnedColumns?: string[];
+ supportedFilterTypes: string[] | undefined;
+ // table-injected metadata
+ metadata: object;
+
+ constructor({
+ info = {},
+ data,
+ color,
+ metadata,
+ supportedFilterTypes
+ }: {
+ info?: ProtoDataset['info'];
+ data: ProtoDataset['data'];
+ color: RGBColor;
+ metadata?: ProtoDataset['metadata'];
+ supportedFilterTypes?: ProtoDataset['supportedFilterTypes'];
+ }) {
// TODO - what to do if validation fails? Can kepler handle exceptions?
// const validatedData = validateInputData(data);
// if (!validatedData) {
// return this;
// }
+ // @ts-expect-error
const dataContainer = createDataContainer(data.rows, {fields: data.fields});
const datasetInfo = {
@@ -70,12 +167,13 @@ class KeplerTable {
...(info || {})
};
const dataId = datasetInfo.id;
-
- const fields = data.fields.map((f, i) => ({
+ // @ts-expect-error
+ const fields: Field[] = data.fields.map((f, i) => ({
...f,
fieldIdx: i,
id: f.name,
displayName: f.displayName || f.name,
+ // @ts-expect-error
valueAccessor: maybeToDate.bind(
null,
// is time
@@ -113,7 +211,7 @@ class KeplerTable {
* Get field
* @param columnName
*/
- getColumnField(columnName) {
+ getColumnField(columnName: string): Field | undefined {
const field = this.fields.find(fd => fd[FID_KEY] === columnName);
this._assetField(columnName, field);
return field;
@@ -123,7 +221,7 @@ class KeplerTable {
* Get fieldIdx
* @param columnName
*/
- getColumnFieldIdx(columnName) {
+ getColumnFieldIdx(columnName: string): number {
const fieldIdx = this.fields.findIndex(fd => fd[FID_KEY] === columnName);
this._assetField(columnName, Boolean(fieldIdx > -1));
return fieldIdx;
@@ -132,7 +230,7 @@ class KeplerTable {
/**
* Get the value of a cell
*/
- getValue(columnName, rowIdx) {
+ getValue(columnName: string, rowIdx: number): any {
const field = this.getColumnField(columnName);
return field ? field.valueAccessor({index: rowIdx}) : null;
}
@@ -142,23 +240,23 @@ class KeplerTable {
* @param fieldIdx
* @param newField
*/
- updateColumnField(fieldIdx, newField) {
+ updateColumnField(fieldIdx: number, newField: Field): void {
this.fields = Object.assign([...this.fields], {[fieldIdx]: newField});
}
/**
* Update dataset color by custom color
- * @param {import('reducers/types').RGBColor} newColor
+ * @param newColor
*/
- updateTableColor(newColor) {
+ updateTableColor(newColor: RGBColor): void {
this.color = newColor;
}
/**
* Save filterProps to field and retrieve it
- * @param {string} columnName
+ * @param columnName
*/
- getColumnFilterProps(columnName) {
+ getColumnFilterProps(columnName: string): Field['filterProps'] | null | undefined {
const fieldIdx = this.getColumnFieldIdx(columnName);
if (fieldIdx < 0) {
return null;
@@ -173,7 +271,6 @@ class KeplerTable {
return null;
}
- // @ts-expect-error
const filterProps = getFilterProps(field, fieldDomain);
const newField = {
...field,
@@ -191,7 +288,7 @@ class KeplerTable {
* @param layers
* @param opt
*/
- filterTable(filters, layers, opt) {
+ filterTable(filters: Filter[], layers: Layer[], opt?: FilterDatasetOpt): KeplerTable {
const {dataContainer, id: dataId, filterRecord: oldFilterRecord, fields} = this;
// if there is no filters
@@ -216,7 +313,7 @@ class KeplerTable {
const shouldCalDomain = Boolean(this.changedFilters.dynamicDomain);
const shouldCalIndex = Boolean(this.changedFilters.cpu);
- let filterResult = {};
+ let filterResult: FilterResult = {};
if (shouldCalDomain || shouldCalIndex) {
const dynamicDomainFilters = shouldCalDomain ? filterRecord.dynamicDomain : null;
const cpuFilters = shouldCalIndex ? filterRecord.cpu : null;
@@ -249,7 +346,7 @@ class KeplerTable {
* @param filters
* @param layers
*/
- filterTableCPU(filters, layers) {
+ filterTableCPU(filters: Filter[], layers: Layer[]): KeplerTable {
const opt = {
cpuOnly: true,
ignoreDomain: true
@@ -287,7 +384,7 @@ class KeplerTable {
* Calculate field domain based on field type and data
* for Filter
*/
- getColumnFilterDomain(field) {
+ getColumnFilterDomain(field: Field): FieldDomain {
const {dataContainer} = this;
const {valueAccessor} = field;
@@ -318,7 +415,10 @@ class KeplerTable {
/**
* Get the domain of this column based on scale type
*/
- getColumnLayerDomain(field, scaleType) {
+ getColumnLayerDomain(
+ field: Field,
+ scaleType: string
+ ): number[] | string[] | [number, number] | null {
const {dataContainer, filteredIndexForDomain} = this;
if (!SCALE_TYPES[scaleType]) {
@@ -369,7 +469,7 @@ class KeplerTable {
* @param fieldName
* @param condition
*/
- _assetField(fieldName, condition) {
+ _assetField(fieldName: string, condition: any): void {
if (!condition) {
Console.error(`${fieldName} doesnt exist in dataset ${this.id}`);
}
@@ -390,13 +490,12 @@ export function removeSuffixAndDelimiters(layerName, suffix) {
*
* @param fields
* @returns found point fields
- * @type {typeof import('./kepler-table').findPointFieldPairs}
*/
-export function findPointFieldPairs(fields) {
+export function findPointFieldPairs(fields: Field[]): FieldPair[] {
const allNames = fields.map(f => f.name.toLowerCase());
// get list of all fields with matching suffixes
- const acc = [];
+ const acc: FieldPair[] = [];
return allNames.reduce((carry, fieldName, idx) => {
// This search for pairs will early exit if found.
for (const suffixPair of TRIP_POINT_FIELDS) {
@@ -437,9 +536,13 @@ export function findPointFieldPairs(fields) {
* @param dataset
* @param column
* @param mode
- * @type {typeof import('./kepler-table').sortDatasetByColumn}
+ * @type
*/
-export function sortDatasetByColumn(dataset, column, mode) {
+export function sortDatasetByColumn(
+ dataset: KeplerTable,
+ column: string,
+ mode?: string
+): KeplerTable {
const {allIndexes, fields, dataContainer} = dataset;
const fieldIndex = fields.findIndex(f => f.name === column);
if (fieldIndex < 0) {
@@ -470,10 +573,7 @@ export function sortDatasetByColumn(dataset, column, mode) {
return dataset;
}
-/**
- * @type {typeof import('./kepler-table').pinTableColumns}
- */
-export function pinTableColumns(dataset, column) {
+export function pinTableColumns(dataset: KeplerTable, column: string): KeplerTable {
const field = dataset.getColumnField(column);
if (!field) {
return dataset;
@@ -490,19 +590,15 @@ export function pinTableColumns(dataset, column) {
// @ts-ignore
return copyTableAndUpdate(dataset, {pinnedColumns});
}
-/**
- *
- * @type {typeof import('./kepler-table').copyTable}
- */
-export function copyTable(original) {
+export function copyTable<T extends {}>(original: T): T {
return Object.assign(Object.create(Object.getPrototypeOf(original)), original);
}
/**
- * @type {typeof import('./kepler-table').copyTableAndUpdate}
+ * @type
* @returns
*/
-export function copyTableAndUpdate(original, options = {}) {
+export function copyTableAndUpdate<T extends {}>(original: T, options: Partial<T> = {}): T {
return Object.entries(options).reduce((acc, entry) => {
acc[entry[0]] = entry[1];
return acc;
diff --git a/src/utils/table-utils/row-data-container.d.ts b/src/utils/table-utils/row-data-container.d.ts
deleted file mode 100644
index d5eacf44c..000000000
--- a/src/utils/table-utils/row-data-container.d.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import {ProcessorResult} from 'processors/data-processor';
-import {Field} from './kepler-table';
-import {DataContainerInterface, RangeOptions} from './data-container-interface';
-import {DataRow, SharedRowOptions} from './data-row';
-
-type RowDataContainerInput = {
- rows: any[][],
- fields?: Field[]
-}
-
-/**
- * A data container where all data is stored internally as a 2D array.
- */
-export class RowDataContainer implements DataContainerInterface {
- constructor(data: RowDataContainerInput);
-
- numRows(): number;
- numColumns(): number;
- valueAt(rowIndex: number, columnIndex: number): any;
- row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow;
- rowAsArray(rowIndex: number): any[];
- rows(sharedRow?: SharedRowOptions): Generator<DataRow, void, any>;
- column(columnIndex: number): Generator<any, void, any>;
- flattenData(): any[][];
- getPlainIndex(): number[];
- map(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions, options?: RangeOptions): any[];
- mapIndex(func: ({index: number}, dc: DataContainerInterface) => any, options?: RangeOptions): any[];
- find(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions): DataRow | undefined;
- reduce(func: (acc: any, row: DataRow, index: number) => any, initialValue: any, sharedRow?: SharedRowOptions): any;
-}
diff --git a/src/utils/table-utils/row-data-container.js b/src/utils/table-utils/row-data-container.ts
similarity index 68%
rename from src/utils/table-utils/row-data-container.js
rename to src/utils/table-utils/row-data-container.ts
index 5132d9de2..67b39587c 100644
--- a/src/utils/table-utils/row-data-container.js
+++ b/src/utils/table-utils/row-data-container.ts
@@ -18,13 +18,20 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import {DataRow} from './data-row';
+import {DataRow, SharedRowOptions} from './data-row';
+import {Field} from './kepler-table';
+import {DataContainerInterface, RangeOptions} from './data-container-interface';
+
+type RowDataContainerInput = {
+ rows: any[][];
+ fields?: Field[];
+};
/**
- * @param {import('./data-container-interface').DataContainerInterface} dataContainer
- * @param {import('./data-row').SharedRowOptions} sharedRow
+ * @param dataContainer
+ * @param sharedRow
*/
-function* rowsIterator(dataContainer, sharedRow) {
+function* rowsIterator(dataContainer: DataContainerInterface, sharedRow: SharedRowOptions) {
const numRows = dataContainer.numRows();
for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
yield dataContainer.row(rowIndex, sharedRow);
@@ -32,18 +39,24 @@ function* rowsIterator(dataContainer, sharedRow) {
}
/**
- * @param {import('./data-container-interface').DataContainerInterface} dataContainer
- * @param {number} columnIndex
+ * @param dataContainer
+ * @param columnIndex
*/
-function* columnIterator(dataContainer, columnIndex) {
+function* columnIterator(dataContainer: DataContainerInterface, columnIndex: number) {
const numRows = dataContainer.numRows();
for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
yield dataContainer.valueAt(rowIndex, columnIndex);
}
}
-export class RowDataContainer {
- constructor(data) {
+/**
+ * A data container where all data is stored internally as a 2D array.
+ */
+export class RowDataContainer implements DataContainerInterface {
+ _rows: any[][];
+ _numColumns: number;
+
+ constructor(data: RowDataContainerInput) {
if (!data.rows) {
throw Error('RowDataContainer: no rows provided');
}
@@ -56,22 +69,22 @@ export class RowDataContainer {
this._numColumns = data.rows[0]?.length || 0;
}
- numRows() {
+ numRows(): number {
return this._rows.length;
}
- numColumns() {
+ numColumns(): number {
return this._numColumns;
}
- valueAt(rowIndex, columnIndex) {
+ valueAt(rowIndex: number, columnIndex: number): any {
if (this._rows[rowIndex] === null) {
return null;
}
return this._rows[rowIndex][columnIndex];
}
- row(rowIndex, sharedRow) {
+ row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow {
const tSharedRow = DataRow.createSharedRow(sharedRow);
if (tSharedRow) {
tSharedRow.setSource(this, rowIndex);
@@ -81,34 +94,38 @@ export class RowDataContainer {
return new DataRow(this, rowIndex);
}
- rowAsArray(rowIndex) {
+ rowAsArray(rowIndex: number): any[] {
return this._rows[rowIndex];
}
- rows(sharedRow) {
+ rows(sharedRow: SharedRowOptions) {
const tSharedRow = DataRow.createSharedRow(sharedRow);
return rowsIterator(this, tSharedRow);
}
- column(columnIndex) {
+ column(columnIndex: number) {
return columnIterator(this, columnIndex);
}
- flattenData() {
+ flattenData(): any[][] {
return this._rows;
}
- getPlainIndex(valid) {
+ getPlainIndex(): number[] {
return this._rows.map((_, i) => i);
}
- map(func, sharedRow, options = {}) {
+ map<T>(
+ func: (row: DataRow, index: number) => T,
+ sharedRow?: SharedRowOptions,
+ options: RangeOptions = {}
+ ): T[] {
const tSharedRow = DataRow.createSharedRow(sharedRow);
const {start = 0, end = this.numRows()} = options;
const endRow = Math.min(this.numRows(), end);
- const out = [];
+ const out: T[] = [];
for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
const row = this.row(rowIndex, tSharedRow);
out.push(func(row, rowIndex));
@@ -116,18 +133,24 @@ export class RowDataContainer {
return out;
}
- mapIndex(func, options = {}) {
+ mapIndex<T>(
+ func: ({index: number}, dc: DataContainerInterface) => T,
+ options: RangeOptions = {}
+ ): T[] {
const {start = 0, end = this.numRows()} = options;
const endRow = Math.min(this.numRows(), end);
- const out = [];
+ const out: T[] = [];
for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
out.push(func({index: rowIndex}, this));
}
return out;
}
- find(func, sharedRow) {
+ find(
+ func: (row: DataRow, index: number) => boolean,
+ sharedRow?: SharedRowOptions
+ ): DataRow | undefined {
const tSharedRow = DataRow.createSharedRow(sharedRow);
for (let rowIndex = 0; rowIndex < this._rows.length; ++rowIndex) {
@@ -139,7 +162,11 @@ export class RowDataContainer {
return undefined;
}
- reduce(func, initialValue, sharedRow) {
+ reduce<T>(
+ func: (acc: T, row: DataRow, index: number) => T,
+ initialValue: T,
+ sharedRow?: SharedRowOptions
+ ): T {
const tSharedRow = DataRow.createSharedRow(sharedRow);
for (let rowIndex = 0; rowIndex < this._rows.length; ++rowIndex) {
diff --git a/test/helpers/comparison-utils.js b/test/helpers/comparison-utils.js
index b754c8c00..42b3f650f 100644
--- a/test/helpers/comparison-utils.js
+++ b/test/helpers/comparison-utils.js
@@ -24,8 +24,12 @@ import KeplerTable from '../../src/utils/table-utils/kepler-table';
export function cmpObjectKeys(t, expectedObj, actualObj, name) {
t.deepEqual(
- Object.keys(actualObj).sort(),
- Object.keys(expectedObj).sort(),
+ Object.keys(actualObj)
+ .filter(key => actualObj[key] !== undefined)
+ .sort(),
+ Object.keys(expectedObj)
+ .filter(key => expectedObj[key] !== undefined)
+ .sort(),
`${name} should have same keys`
);
}
@@ -231,51 +235,53 @@ export function cmpDataset(t, expectedDataset, actualDataset, opt = {}) {
cmpObjectKeys(t, expectedDataset, actualDataset, `dataset:${expectedDataset.id}`);
// test everything except auto generated color
- Object.keys(actualDataset).forEach(key => {
- switch (key) {
- case 'fields':
- cmpFields(t, expectedDataset.fields, actualDataset.fields, expectedDataset.id);
- break;
- case 'gpuFilter':
- // test gpuFilter props
- cmpGpuFilterProp(
- t,
- expectedDataset.gpuFilter,
- actualDataset.gpuFilter,
- actualDataset.dataContainer
- );
- break;
- case 'filterRecord':
- case 'filterRecordCPU':
- cmpObjectKeys(
- t,
- expectedDataset[key],
- actualDataset[key],
- `dataset.${expectedDataset.id}.${key}`
- );
- Object.keys(expectedDataset[key]).forEach(item => {
- t.ok(
- Array.isArray(expectedDataset[key][item]),
- `dataset.${expectedDataset.id}[key].${item} should be an array`
- );
- // compare filter name
- t.deepEqual(
- actualDataset[key][item].map(f => f.name),
- expectedDataset[key][item].map(f => f.name),
- `dataset.${expectedDataset.id}.${key}.${item} should contain correct filter`
+ Object.keys(actualDataset)
+ .filter(key => actualDataset[key] !== undefined)
+ .forEach(key => {
+ switch (key) {
+ case 'fields':
+ cmpFields(t, expectedDataset.fields, actualDataset.fields, expectedDataset.id);
+ break;
+ case 'gpuFilter':
+ // test gpuFilter props
+ cmpGpuFilterProp(
+ t,
+ expectedDataset.gpuFilter,
+ actualDataset.gpuFilter,
+ actualDataset.dataContainer
);
- });
- break;
- default:
- if (key !== 'color' || opt.color) {
- t.deepEqual(
- actualDataset[key],
+ break;
+ case 'filterRecord':
+ case 'filterRecordCPU':
+ cmpObjectKeys(
+ t,
expectedDataset[key],
- `dataset.${expectedDataset.id}.${key} should be correct`
+ actualDataset[key],
+ `dataset.${expectedDataset.id}.${key}`
);
- }
- }
- });
+ Object.keys(expectedDataset[key]).forEach(item => {
+ t.ok(
+ Array.isArray(expectedDataset[key][item]),
+ `dataset.${expectedDataset.id}[key].${item} should be an array`
+ );
+ // compare filter name
+ t.deepEqual(
+ actualDataset[key][item].map(f => f.name),
+ expectedDataset[key][item].map(f => f.name),
+ `dataset.${expectedDataset.id}.${key}.${item} should contain correct filter`
+ );
+ });
+ break;
+ default:
+ if (key !== 'color' || opt.color) {
+ t.deepEqual(
+ actualDataset[key],
+ expectedDataset[key],
+ `dataset.${expectedDataset.id}.${key} should be correct`
+ );
+ }
+ }
+ });
}
export function cmpGpuFilterProp(t, expectedGpuFilter, actualGpuFilter, dataContainer) {
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index c3e1efa5a..9144ab1f5 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -4616,8 +4616,6 @@ test('#visStateReducer -> APPLY_CPU_FILTER has multi datasets', t => {
test('#visStateReducer -> SORT_TABLE_COLUMN', t => {
const initialState = CloneDeep(StateWFiles.visState);
- const previousDataset1 = initialState.datasets[testCsvDataId];
- const previousKeys = Object.keys(previousDataset1);
// sort with default mode
const nextState = reducer(initialState, VisStateActions.sortTableColumn());
@@ -4656,14 +4654,6 @@ test('#visStateReducer -> SORT_TABLE_COLUMN', t => {
22,
21
];
- const newKeys = Object.keys(nextState2.datasets[testCsvDataId]);
- const addedKeys = newKeys.filter(k => !previousKeys.includes(k));
-
- t.deepEqual(
- addedKeys,
- ['sortColumn', 'sortOrder'],
- 'should add sortColumn and sortOrder to dataset'
- );
t.deepEqual(nextState2.datasets[testCsvDataId].sortOrder, expectedOrder, 'should sort correctly');
t.deepEqual(
nextState2.datasets[testCsvDataId].sortColumn,
@@ -4738,8 +4728,6 @@ test('#visStateReducer -> updateTableColor', t => {
test('#visStateReducer -> PIN_TABLE_COLUMN', t => {
const initialState = CloneDeep(StateWFiles.visState);
- const previousDataset1 = initialState.datasets[testCsvDataId];
-
// pin with empty arg
const nextState = reducer(initialState, VisStateActions.pinTableColumn());
t.equal(nextState, initialState, 'state should not change when input is not given');
@@ -4750,10 +4738,6 @@ test('#visStateReducer -> PIN_TABLE_COLUMN', t => {
VisStateActions.pinTableColumn(testCsvDataId, 'gps_data.lat')
);
- const newKeys = Object.keys(nextState1.datasets[testCsvDataId]);
- const addedKeys = newKeys.filter(k => !Object.keys(previousDataset1).includes(k));
-
- t.deepEqual(addedKeys, ['pinnedColumns'], 'should add pinnedColumns to dataset');
assertDatasetIsTable(t, nextState1.datasets[testCsvDataId]);
t.deepEqual(