UNPKG

haystack-core

Version:
1,818 lines (1,804 loc) 237 kB
/** * The type of token */ declare enum TokenType { eof = 0, text = 1, paths = 2, string = 3, number = 4, date = 5, time = 6, uri = 7, ref = 8, boolean = 9, symbol = 10, equals = 11, notEquals = 12, lessThan = 13, lessThanOrEqual = 14, greaterThan = 15, greaterThanOrEqual = 16, leftBrace = 17, rightBrace = 18, rel = 19, wildcardEq = 20 } /** * Haystack kind enumeration. */ declare enum Kind { Str = "str", Number = "number", Date = "date", Time = "time", Uri = "uri", Ref = "ref", Bool = "bool", Dict = "dict", DateTime = "dateTime", Marker = "marker", Remove = "remove", NA = "na", Coord = "coord", XStr = "xstr", Bin = "bin", Symbol = "symbol", List = "list", Grid = "grid" } /** * Haystack JSON format types. * * As described in https://bitbucket.org/finproducts/hayson/src/master/ * * @module */ type HaysonNumVal = number | string; interface HaysonNum { _kind?: Kind; val: HaysonNumVal; unit?: string; } interface HaysonSingleton { _kind?: Kind; } type HaysonMarker = HaysonSingleton; type HaysonNa = HaysonSingleton; type HaysonRemove = HaysonSingleton; interface HaysonRef { _kind?: Kind; val: string; dis?: string; } interface HaysonKindVal { _kind?: Kind; val: string; } type HaysonUri = HaysonKindVal; type HaysonSymbol = HaysonKindVal; type HaysonTime = HaysonKindVal; type HaysonDate = HaysonKindVal; interface HaysonDateTime { _kind?: Kind; val: string; tz?: string; } interface HaysonCoord { _kind?: Kind; lat: number; lng: number; } interface HaysonXStr { _kind?: Kind; type: string; val: string; } type HaysonVal = string | number | boolean | HaysonNum | HaysonSingleton | HaysonRef | HaysonTime | HaysonDate | HaysonUri | HaysonDateTime | HaysonSymbol | HaysonCoord | HaysonXStr | HaysonList | HaysonDict | HaysonGrid | null; interface HaysonList extends Array<HaysonVal> { } interface HaysonDict { [prop: string]: HaysonVal; } interface HaysonGrid { _kind: Kind; meta: HaysonDict; cols: { name: string; meta?: HaysonDict; }[]; rows: HaysonDict[]; } /** * The MIME type for Haystack JSON (a.k.a Hayson) */ declare const HAYSON_MIME_TYPE = "application/vnd.haystack+json"; /** * Base token definitions. * * @module */ /** * A token created when parsing a string. */ interface Token { /** * @returns The type of token. */ type: TokenType; /** * Returns true if the type matches this token's type. * * @param type The token type. * @return True if the type matches. */ is(type: TokenType): boolean; /** * Returns true if the object matches this one. * * @param type The token type. * @param text The text. * @return True if the objects are equal. */ equals(token: Token): boolean; /** * @returns A string representation of the token. */ toString(): string; /** * Encodes to an encoded zinc value that can be used * in a haystack filter string. * * The encoding for a haystack filter is mostly zinc but contains * some exceptions. * * @returns The encoded value that can be used in a haystack filter. */ toFilter(): string; /** * @returns A JSON representation of the token. */ toJSON(): { type: string; [prop: string]: string | string[] | HaysonVal; }; } /** * A token object with some parsed text. */ declare class TokenObj implements Token { /** * The token type. */ readonly type: TokenType; /** * The token text value. */ readonly text: string; /** * Flag used to identify a token object. */ readonly _isATokenObj = true; /** * Contructs a new token value. * * @param type The token type. * @param text The token's text. * @param value The tokens value. */ constructor(type: TokenType, text: string); /** * @returns The text value as a paths array. */ get paths(): string[]; /** * Returns true if the type matches this token's type. * * @param type The token type. * @return True if the type matches. */ is(type: TokenType): boolean; /** * Returns true if the object matches this one. * * @param type The token type. * @param text The text. * @return True if the objects are equal. */ equals(token: Token): boolean; /** * @returns A string representation of the token. */ toString(): string; /** * @returns The encoded value that can be used in a haystack filter. */ toFilter(): string; /** * @returns A JSON representation of the token. */ toJSON(): { type: string; [prop: string]: string | string[] | HaysonVal; }; } /** * Test to see if the value is an instance of a token object. */ declare function isTokenObj(value: unknown): value is TokenObj; /** * Haystack version 3 JSON format types. * * As described in https://project-haystack.org/doc/docHaystack/Json * * Please note, this has been supplanted by the newer `Hayson` JSON format... * * https://bitbucket.org/finproducts/hayson/src/master/ * * @module */ type JsonV3Num = `n:${string}`; type JsonV3Marker = 'm:'; type JsonV3Na = 'z:'; type JsonV3Remove = '-:'; type JsonV3Ref = `r:${string}`; type JsonV3Uri = `u:${string}`; type JsonV3Symbol = `y:${string}`; type JsonV3Time = `h:${string}`; type JsonV3Date = `d:${string}`; type JsonV3DateTime = `t:${string}`; type JsonV3Coord = `c:${string}`; type JsonV3XStr = `x:${string}`; type JsonV3Val = boolean | string | JsonV3Num | JsonV3Ref | JsonV3Time | JsonV3Date | JsonV3Uri | JsonV3DateTime | JsonV3Symbol | JsonV3Coord | JsonV3XStr | JsonV3List | JsonV3Dict | JsonV3Grid | JsonV3Marker | JsonV3Na | JsonV3Remove | null; type JsonV3List = Array<JsonV3Val>; interface JsonV3Dict { [prop: string]: JsonV3Val; } interface JsonV3Grid { meta?: JsonV3Dict; cols?: { name: string; [prop: string]: JsonV3Val; }[]; rows?: JsonV3Dict[]; } /** * The MIME type for the older Haystack version 3 JSON. */ declare const JSON_V3_MIME_TYPE = "application/vnd.haystack+json;version=3"; declare const GRID_COLUMN_SYMBOL: unique symbol; /** * A grid column. */ declare class GridColumn { /** * Name of the column. */ readonly name: string; /** * Meta data for the column. */ readonly meta: HDict; /** * Constructs a new column. * * @param name The name of the column. * @param meta The column's meta data. */ constructor(name: string, meta?: HDict); /** * @returns The display name for the column. */ get dis(): string; /** * @returns The display name for the column. */ get displayName(): string; /** * Column equality check. * * @param column The column to test. * @returns True if the value is the same. */ equals(column: GridColumn): boolean; /** * Flag used to identify a grid column. */ [GRID_COLUMN_SYMBOL]: symbol; } /** * Returns true if the value is a grid column. * * @param value The value. * @returns True if the value is a grid column. */ declare function isGridColumn(value: unknown): value is GridColumn; declare const GRID_STORE_SYMBOL: unique symbol; /** * The default grid version number. */ declare const DEFAULT_GRID_VERSION = "3.0"; /** * The grid's version tag name. */ declare const GRID_VERSION_NAME = "ver"; /** * Implements the storage for an HGrid. * * This separates the HGrid interface from the actual storage, * which could be backed by a native one. */ interface GridStore<DictVal extends HDict> { /** * The grid's version number. */ version: string; /** * The stores's meta data. */ meta: HDict; /** * The stores's columns. */ columns: GridColumn[]; /** * The store's rows. */ rows: DictVal[]; /** * @returns A JSON reprentation of the grid. */ toJSON(): HaysonGrid; /** * @returns A string containing the JSON representation of the object. */ toJSONString(): string; /** * @returns A byte buffer that has an encoded JSON string representation of the object. */ toJSONUint8Array(): Uint8Array; /** * Indicates this is a grid store. */ readonly [GRID_STORE_SYMBOL]: symbol; } /** * Type guard to check whether the value is a grid store. * * @param value The value to test. * @returns true if the object is a grid store. */ declare function isGridStore<DictVal extends HDict>(value: unknown): value is GridStore<DictVal>; /** * An iterator for dicts. */ declare class GridDictIterator<DictVal extends HDict> implements Iterator<DictVal> { #private; constructor(grid: HGrid); next(): IteratorResult<DictVal>; } interface GridParams<DictVal extends HDict = HDict> { meta?: HDict | HaysonDict; columns?: { name: string; meta?: HDict | HaysonDict; }[]; cols?: { name: string; meta?: HDict | HaysonDict; }[]; rows?: (DictVal | HaysonDict)[]; version?: string; } /** * A haystack grid. * * ```typescript * const grid = new HGrid({ * columns: [ * { * name: 'name' * }, * { * name: 'height' * } * ], * // rows * rows: [ * new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }), * new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') }) * ] * }) * * // The same grid can be specified without any rows. The columns will be dynamically * // generated based upon the row data... * const grid0 = new HGrid({ * rows: [ * new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }), * new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') }) * ] * }) * * // The same grid can be created from a Hayson object. * // Again columns don't have to be specified unless precise order and meta data is required... * const grid1 = new HGrid({ * rows: [ * { name: 'Mall', height: { _kind: 'number', val: 200, unit: 'm' } }, * { name: 'House', height: { _kind: 'number', val: 30, unit: 'm' } }, * ] * }) * * // Iterate a grid * for (let dict of grid) { * console.log(dict) * } * * // Filter a grid * const filteredGrid = grid.filter('name == "House"') * console.log(filteredGrid) * * // Test a grid * if (grid.has('name == "House"')) { * console.log('Found house!') * } * * // Remove items from a grid * grid.remove('name == "Mall"') * * // Average, sum, max and min... * console.log(grid.avgOf('height')) * console.log(grid.sumOf('height')) * console.log(grid.maxOf('height')) * console.log(grid.minOf('height')) * ``` */ declare class HGrid<DictVal extends HDict = HDict> implements HVal, Iterable<DictVal> { /** * The internal grid storage. */ private readonly $store; /** * An internal column index cache. * * This is used to increase the performance of column name look ups. */ private $columnNameCache; /** * Numerical index access. */ [prop: number]: DictVal | undefined; /** * Constructs a new grid. * * ```typescript * const grid = new HGrid({ * columns: [ * { * name: 'name' * }, * { * name: 'height' * } * ], * // rows * rows: [ * new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }), * new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') }) * ] * }) * * // The same grid can be specified without any rows. The columns will be dynamically * // generated based upon the row data... * const grid0 = new HGrid({ * rows: [ * new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }), * new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') }) * ] * }) * * // The same grid can be created from a Hayson object. * // Again columns don't have to be specified unless precise order and meta data is required... * const grid1 = new HGrid({ * rows: [ * { name: 'Mall', height: { _kind: 'number', val: 200, unit: 'm' } }, * { name: 'House', height: { _kind: 'number', val: 30, unit: 'm' } }, * ] * }) * * // Pass in a haystack value to create a grid... * const grid3 = new HGrid(HNum.make(24)) // Creates a grid with one column called 'val' and one row. * * // Pass in an array of dicts to create a grid... * const grid4 = new HGrid([ * new HDict({ name: HStr.make('Mall'), height: HNum.make(200, 'm') }), * new HDict({ name: HStr.make('House'), height: HNum.make(30, 'm') }) * ]) * * // Pass in an array of Hayson dicts to create a grid... * const grid5 = new HGrid([ * { name: 'Mall', height: { _kind: 'number', val: 200, unit: 'm' } }, * { name: 'House', height: { _kind: 'number', val: 30, unit: 'm' } }, * ]) * ``` * * @param value The values used to create a grid. */ constructor(arg?: GridParams<DictVal> | HaysonGrid | HVal | (HaysonDict | DictVal)[] | GridStore<DictVal>); /** * Implement proxy to make it easy to get and set internal values. */ private makeProxy; private get columnNameCache(); private rebuildColumnCache; /** * Makes a new grid. * * @param value The values used to create a grid. * @returns A grid. */ static make<DictVal extends HDict = HDict>(arg?: GridParams<DictVal> | HaysonGrid | HVal | (HaysonDict | DictVal)[]): HGrid<DictVal>; /** * @returns The grid's version number. */ get version(): string; /** * Sets the grid's version number. */ set version(version: string); /** * The grid's meta data. */ get meta(): HDict; /** * @returns The value's kind. */ getKind(): Kind; /** * Compares the value's kind. * * @param kind The kind to compare against. * @returns True if the kind matches. */ isKind(kind: Kind): boolean; /** * @returns A JSON reprentation of the object. */ toJSON(): HaysonGrid; /** * @returns A string containing the JSON representation of the object. */ toJSONString(): string; /** * @returns A byte buffer that has an encoded JSON string representation of the object. */ toJSONUint8Array(): Uint8Array; /** * @returns A JSON v3 representation of the object. */ toJSONv3(): JsonV3Grid; /** * Encodes to an encoded zinc value that can be used * in a haystack filter string. * * A grid isn't supported in filter so throw an error. * * @returns The encoded value that can be used in a haystack filter. */ toFilter(): string; /** * Encodes to an encoding zinc value. * * @param nested An optional flag used to indiciate whether the * value being encoded is nested. * @returns The encoded zinc string. */ toZinc(nested?: boolean): string; /** * @returns An Axon encoded string. */ toAxon(): string; /** * Grid equality check. * * @param value The value to test. * @returns True if the value is the same. */ equals(value: unknown): boolean; /** * Compares two grids. * * @param value The value to compare against. * @returns The sort order as negative, 0, or positive. */ compareTo(value: unknown): number; /** * Return all the rows of the grid. * * ```typescript * const anArrayOfDicts = grid.getRows() * ``` * * @returns All rows in the grid. */ getRows(): DictVal[]; /** * Return a row or undefined if it can't find it via its * row number. * * ```typescript * // Get a dict at a given index or returned undefined if it can't be found. * const dict = grid.get(0) * if (dict) { * // Do something * } * ``` * * @param index The index number of the row. * @returns The dict or undefined if it does not exist. */ get(index: number): DictVal | undefined; /** * Return the first row in the grid or undefined if it can't be found. * * ```typescript * const dict = grid.first * if (dict) { * // Do something * } * ``` * * @returns The dict or undefined if it does not exist. */ get first(): DictVal | undefined; /** * Return the last row in the grid or undefined if it can't be found. * * ```typescript * const dict = grid.last * if (dict) { * // Do something * } * ``` * * @returns The dict or undefined if it does not exist. */ get last(): DictVal | undefined; /** * Remove the row from the grid via its index number of a haystack filter. * * ```typescript * // Remove a row via its index * grid.remove(0) * * // Remove multiple rows via a Haystack Filter * grid.remove('foo == "baa"') * ``` * * @param filter A haystack filter, index number or AST node. * @param cx Optional haystack filter evaluation context. * @returns The rows that were removed. If no rows were removed then the is empty. */ remove(filter: number | string | Node, cx?: Partial<EvalContext>): DictVal[]; /** * Filter the grid with the haystack filter and return a new grid with the results. * * ```typescript * // Filter a grid with a haystack filter * const newGridWithFoo = grid.filter('foo') * * // Filter a grid with a function callback * const newGridWithFooAgain = grid.filter((row: HDict): boolean => row.has('foo')) * ``` * * @param filter The haystack filter, AST node or filter function callback. * @param cx Optional haystack filter evaluation context. * @returns A new filtered grid. */ filter(filter: string | Node | ((row: DictVal, index: number) => boolean), cx?: Partial<EvalContext>): HGrid<DictVal>; /** * Synchronize column meta information from this grid to the specified grid. * * @param grid The grid to synchronize data to. */ private syncColumnMeta; /** * Filters an individual column in a grid. * * For example, if a particular column in a grid holds a list. * The inner filter can be run against all of the list values * held in that column. * * The filter can be run against a list, dict or grid. * * ```typescript * const grid = HGrid.make({ * rows: [ * { list: [ 'foo', 'boo', 'goo' ] }, * { list: [ 'foo', 'boo1', 'goo1' ] }, * { list: [ 'doo', 'boo1', 'goo1' ] }, * ] * }) * * // Returns a grid with only the first two rows. * const newGrid = grid.filterBy('list', 'item == "foo"') * ``` * * @param name The name of the column that holds the list values. * @param innerFilter The haystack filter to run against the list. * @param cx Optional haystack filter evaluation context. * @returns A filtered grid. */ filterBy(name: string, innerFilter: string | Node, cx?: Partial<EvalContext>): HGrid<DictVal>; /** * Provide a grid with unique values in the specified columns. * * ```typescript * const grid = HGrid.make({ * rows: [ * { id: 1, name: 'Jason' }, * { id: 2, name: 'Gareth' }, * { id: 3, name: 'Gareth' }, * ] * }) * * // Returns a new grid with rows 1 and 2. * const uniqueGrid = grid.unique('name') * ``` * * @param names The column names. * @returns The filtered grid instance. */ uniqueBy(names: string | string[]): HGrid<DictVal>; /** * Return true if the filter matches at least one row. * * ```typescript * if (grid.any('site')) { * // The grid has some sites. * } * ``` * * @param filter The haystack filter or AST node. * @param cx Optional haystack filter evaluation context. * @returns true if there's at least one match */ any(filter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Return the first row dict that matches the filter or undefined if nothing is found. * * ```typescript * const dict = grid.find('site')) * ``` * * @param filter The haystack filter or AST node. * @param cx Optional haystack filter evaluation context. * @returns The first row dict that matches the filter. */ find(filter: string | Node, cx?: Partial<EvalContext>): DictVal | undefined; /** * Returns true if the haystack filter matches the value. * * This is the same as the `any` method. * * ```typescript * if (grid.matches('site')) { * // The grid has some sites. * } * ``` * * @param filter The filter to test. * @param cx Optional haystack filter evaluation context. * @returns True if the filter matches ok. */ matches(filter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Return true if the filter matches at least one cell * in a particular column in the grid. * * This filter runs on the data held in the particular column. * * ```typescript * const grid = HGrid.make({ * rows: [ * { list: [ 'foo', 'boo', 'goo' ] }, * { list: [ 'foo', 'boo1', 'goo1' ] }, * { list: [ 'doo', 'boo1', 'goo1' ] }, * ] * }) * * if (grid.anyBy('list', 'item === "foo"')) { * // One or more of the items in the list contains 'foo' * } * ``` * * @param filter The haystack filter or AST node. * @param cx Optional haystack filter evaluation context. * @returns true if there's at least one match */ anyBy(name: string, innerFilter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Return true if the filter matches at least one row. * * ```typescript * const grid = HGrid.make({ * rows: [ * { name: 'Fred' }, * { name: 'Fred' }, * { name: 'Fred' }, * ] * }) * * if (grid.all('name == "Fred")) { * // All rows in the grid have the name Fred. * } * ``` * * @param filter The haystack filter or AST node. * @param cx Optional haystack filter evaluation context. * @returns true if there's at least one match */ all(filter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Return true if the filter matches all the values * in a particular column in the grid. * * This filter runs on the data held in the particular column. * * ```typescript * const grid = HGrid.make({ * rows: [ * { list: [ 'foo', 'foo', 'foo' ] }, * { list: [ 'foo', 'foo', 'foo' ] }, * { list: [ 'foo', 'foo', 'foo' ] }, * ] * }) * * if (grid.allBy('list', 'item == "foo"')) { * // True if all the lists contain all foos. * } * ``` * * @param filter The haystack filter or AST node. * @param cx Optional haystack filter evaluation context. * @returns true if there's at least one match */ allBy(name: string, innerFilter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Run the filter. For each match invoke the callback function. * * The callback takes a match flag, a row and an index argument. If false is returned * the filter stops running. * * @param filter The haystack filter to run or an AST node. * @param callback The callback invoked for each match. * @param cx Optional haystack filter evaluation context. */ private runFilter; /** * Return a function that when called will search for a * dict (record) via its id. * * The method lazily optimizes the request by indexing the grid's id. * * @returns The evaluation context resolve method for a grid. */ private makeResolveFunc; /** * A mapping function that maps from an array of dicts into something else. * * ```typescript * // Map each row to a div using React... * grid.map((dict: HDict) => <div>{dict.toZinc()}</div>>) * ``` * * @param callback A mapping callback that takes a row dict, an index number * and returns a new value. */ map<U>(callback: (row: DictVal, index: number) => U): U[]; /** * Reduce the rows in a grid. * * ```typescript * // Reduce the grid down to one row... * grid = HGrid.make({ * rows: [ * { a: 1, b: 2 }, * { a: 3, b: 4 }, * ], * }) * * grid.reduce((prev, cur): HGrid => { * const dict = prev.get(0) * * if (dict) { * dict.set('a', Number(cur.get<HNum>('a')?.value) + Number(dict.get<HNum>('a')?.value)) * dict.set('b', Number(cur.get<HNum>('b')?.value) + Number(dict.get<HNum>('b')?.value)) * } * * return prev *}, HGrid.make({ rows: [{ a: 0, b: 0 }] })) * ``` * * @param callback The reducer callback. This method will be called with the previous and * current rows (dicts) as well as the index number. * @param initialValue Optional initial value for the reduce. */ reduce<U = DictVal>(callback: (prev: U, current: DictVal, currentIndex: number, array: DictVal[]) => U, initialValue?: U): U; /** * ```typescript * // The number of rows in a grid. * console.log(grid.length) * ``` * * @returns The total number of rows. */ get length(): number; /** * Set the values or dict for an individual row. * * ```typescript * // Set a row in a grid. * grid.set(0, new HDict({ foo: HStr.make('foobar') })) * * // Set a row via Hayson. * grid.set(0, { foo: 'foobar' }) * ``` * * @param index The index number of the row. * @param values The dict or Hayson Dict. * @returns The grid instance. * @throws An error if the index is invalid or the number of rows incorrect. */ set(index: number, values: DictVal | HaysonDict): this; /** * Refreshes a grid's columns based upon the rows in the grid. */ refreshColumns(): void; /** * Adds any missing columns for the dict. * * @param dict The dict to check. */ private addMissingColumns; /** * Add a single or multiple rows using dicts. * * This method can be called in different ways to add multiple rows at a time. * * ```typescript * // Add a single dict. * grid.add(new HDict({ foo: HStr.make('bar') })) * * // Add multiple dicts. * grid.add(new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') })) * * // Add multiple dicts using an array... * grid.add([new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') })]) * * // Same but using Hayson... * grid.add({ foo: 'bar' })) * grid.add({ foo: 'bar' }), { foo: 'bar' }) * grid.add([{ foo: 'bar' }), { foo: 'bar' }]) * ``` * @param rows The rows to add. * @returns The grid instance. * @throws If the values being added are not dicts. */ add(...rows: (DictVal[] | HaysonDict[] | DictVal | HaysonDict)[]): this; /** * Insert rows as dicts at the specified index. * * ```typescript * // Insert a single dict. * grid.insert(1, new HDict({ foo: HStr.make('bar') })) * * // Insert multiple dicts. * grid.insert(1, new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') })) * * // Insert multiple dicts using an array... * grid.insert(1, [new HDict({ foo: HStr.make('bar') }), new HDict({ foo: HStr.make('bar') })]) * * // Same but using Hayson... * grid.insert(1, { foo: 'bar' })) * grid.insert(1, { foo: 'bar' }), { foo: 'bar' }) * grid.insert(1, [{ foo: 'bar' }), { foo: 'bar' }]) * ``` * * @param index The index number to insert the rows at. * @param rows The rows to insert. * @returns The grid instance. * @throws An error if the index is invalid or the rows are not dicts. */ insert(index: number, ...rows: (DictVal[] | HaysonDict[] | DictVal | HaysonDict)[]): this; /** * Sort the grid in ascending order via a column name. This also * supports sorting via multiple column names. * * Precedence is given to the first columns in the table. * * ```typescript * // Sorts the grid in ascending order by 'foo' * grid.sortBy('foo') * * // Sorts the grid in ascending order by 'foo' and then by 'boo' * grid.sortBy(['foo', 'boo']) * ``` * * @param names The name of the column to sort by. * @returns The grid instance. */ sortBy(names: string | string[]): this; /** * Reverses the order of all the rows in the grid. * * ```typescript * // Sort the grid in descending order by foo * grid.sortBy('foo').reverse() * ``` */ reverse(): void; /** * Returns a flattened array of dicts. * * @param rows The rows to flatten into an array of dicts. * @returns An array of dicts. */ private static toDicts; /** * ```typescript * // Create a grid with no rows (still retains column and meta). * grid.clear() * ``` * * Clear all the rows from the grid. */ clear(): void; /** * Return an array of column information. * * ```typescript * // Return an array of column objects. * const cols = grid.getColumns() * ``` * * @returns A copy of the grid's columns. */ getColumns(): GridColumn[]; /** * Return the column names (not display names). * * @returns The column names. */ getColumnNames(): string[]; /** * Add a column and return its new instance. * * If the column is already available then update it. * * ```typescript * grid.addColumn('Address', new HDict({ length: 30 })) * ``` * * @param name The name of the column. * @param meta The column's meta data. * @returns The new column or the one already found. */ addColumn(name: string, meta?: HDict): GridColumn; /** * Does the grid have the specified column? * * ```typescript * if (grid.hasColumn('Address)) { * // The grid has a column called address. * } * ``` * * @param name The name of the column. * @returns True if the grid has the column. */ hasColumn(name: string): boolean; /** * Set the column at the specified index number. * * ```typescript * // Set the column at the specified index with the new name and length. * grid.setColumn(3, 'Address', new HDict({ length: 30 })) * ``` * * @param index The zero based index number of the column. * @param name The name of the column. * @param meta Optional column's meta data. * @returns The updated column. * @throws An error if index does not exist in the columns. */ setColumn(index: number, name: string, meta?: HDict): GridColumn; /** * Returns a grid column via its name or index number. If it can't be found * then return undefined. * * ```typescript * // Get the column at the specified index or return undefined * const col = grid.getColumn('Address') * if (col) { * // Do something * } * * // Alternatively use the column index to get the column * const col1 = grid.getColumn(3) * if (col1) { * // Do something * } * ``` * * @param index The column index number or name. * @returns The column or undefined if not found. */ getColumn(index: number | string): GridColumn | undefined; /** * Returns the number of columns. * * ```typescript * console.log('The table has this many columns: ' + grid.getColumnsLength()) * ``` * * @returns The number of columns. */ getColumnsLength(): number; /** * Reorder the columns with the specified new order of names. * * ```typescript * const grid = HGrid.make({ * columns: [ * { name: 'b' }, * { name: 'c' }, * { name: 'a' }, * ] * }) * * // Reorder the columns to be a, b and then c. * grid.reorderColumns([ 'a', 'b', 'c' ]) * ``` * * @param names The new order of column names to use. */ reorderColumns(names: string | string[]): void; /** * Return a haystack list for all the values in * the specified column. * * If the column can't be found then an empty list is returned. * * ```typescript * const grid = HGrid.make({ * rows: [ * { name: 'Gareth', id: 1 }, * { name: 'Jason', id: 2 }, * { name: 'Radu', id: 3 }, * ] * }) * * // Returns an HList<HStr> of the names (Gareth, Jason and Radu). * const listOfNames = grid.listBy<HStr>('name') * ``` * * @param column The column name, column index or instance to * create the list from. */ listBy<Value extends OptionalHVal>(column: string | number | GridColumn): HList<Value>; /** * Limit the grid only to the specified columns. * * This will return a new instance of a grid. * * ```typescript * grid.filter('site').limitColumns(['id', 'dis']).inspect() * ``` * * @param names The column names. * @returns A new grid instance with the specified columns. */ limitColumns<LimitDictVal extends HDict = DictVal>(names: string[]): HGrid<LimitDictVal>; /** * Iterate over a grid using dicts for rows. * * This enables a 'for ... of' loop to be used directly on an iterator. * * @returns A new iterator for a grid. * * ```typescript * // Iterate a grid * for (let dict of grid) { * console.log(dict) * } * * // Destructure a grid into an array of dicts... * const fooDict = [...grid].filter((dict): boolean => dict.get('foo') === 'foo')[0] * ``` */ [Symbol.iterator](): Iterator<DictVal>; /** * ```typescript * if (grid.isEmpty()) { * // Grid is empty. * } * ``` * * @returns true if the grid is empty. */ isEmpty(): boolean; /** * Selects a range from the grid. * * The start and end can be used to specify a range... * ```typescript * // from [0, 1, 2, 3, 4, 5] to [1, 2, 3, 4] * grid.filter('site').range(1, 4).inspect() * ``` * * //If only the first argument then a quantity can be used... * ```typescript * // select the first 4 rows - [0, 1, 2, 4]... * grid.filter('site').range(4).inspect() * ``` * * @param startOrQuantity The start of the range or quantity. * @param end Optional end range. * @returns This grid instance. */ range(startOrQuantity: number, end?: number): this; /** * Return the sum of values for the specified column. * * ```typescript * const grid = HGrid.make({ * rows: [ * { id: 34, num: 1 }, * { id: 35, num: 2 }, * { id: 36, num: 3 }, * ] * }) * // Sum all the values in the num column (6) * const sum = grid.sumOf('num') * ``` * * @param column The column name, column index or column instance. * @returns The sum of all the numeric values. */ sumOf(column: string | number | GridColumn): number; /** * Return the maximum value in the specified column. * * If there are no numbers then Number.MIN_SAFE_INTEGER is returned. * * ```typescript * const grid = HGrid.make({ * rows: [ * { id: 34, num: 1 }, * { id: 35, num: 2 }, * { id: 36, num: 3 }, * ] * }) * // Return the maximum value in the num column (3). * const max = grid.maxOf('num') * ``` * * @param column The column name, column index or column instance. * @returns The maximum numerical value found. */ maxOf(column: string | number | GridColumn): number; /** * Return the minimum of value in the specified column. * * If there are no numbers then Number.MAX_SAFE_INTEGER is returned. * * ```typescript * const grid = HGrid.make({ * rows: [ * { id: 34, num: 1 }, * { id: 35, num: 2 }, * { id: 36, num: 3 }, * ] * }) * // Return the maximum value in the num column (1). * const min = grid.minOf('num') * ``` * * @param column The column name, column index or column instance. * @returns The minimum numerical value found. */ minOf(column: string | number | GridColumn): number; /** * Return the sum of values for the specified column. * * If there are no numbers then Number.NaN is returned. * * ```typescript * const grid = HGrid.make({ * rows: [ * { id: 34, num: 1 }, * { id: 35, num: 2 }, * { id: 36, num: 3 }, * ] * }) * // Return average of the num column (2). * const avg = grid.avgOf('num') * ``` * * @param column The column name, column index or column instance. * @returns The average of all the numeric values. */ avgOf(column: string | number | GridColumn): number; /** * ```typescript * if (grid.isError()) { * // Do something. * } * ``` * * @returns true if the grid has an error associated with it. */ isError(): boolean; /** * ```typescript * const err = grid.getError() * if (err) { * // Do something with the error. * } * ``` * * @returns Error information or undefined if not available. */ getError(): undefined | { type: string; trace: string; dis: string; }; /** * @returns The grid as an array like object. */ asArrayLike(): ArrayLike<DictVal>; /** * @returns A string representation of the value. */ toString(): string; /** * Dump the value to the local console output. * * @param message An optional message to display before the value. * @returns The value instance. */ inspect(message?: string): this; /** * Check whether the index number for the row is a valid number. * * @param index The row index number to check. * @throws An error if the index number is invalid. */ private checkRowIndexNum; /** * @returns Returns a copy of the grid. */ newCopy(): HGrid<DictVal>; /** * @returns The value as a grid. */ toGrid(): HGrid<DictVal>; /** * @returns The value as a list. */ toList(): HList<DictVal>; /** * @returns The value as a dict. */ toDict(): HDict; } /** * Haystack string. */ declare class HStr implements HVal { #private; /** * Constructs a new haystack string. * * @param value The value. */ private constructor(); /** * Makes a haystack string. * * @param value The value string. * @returns A haystack string. */ static make(value: string | HStr): HStr; /** * @returns The string value. */ get value(): string; set value(value: string); /** * @returns The value's kind. */ getKind(): Kind; /** * Compares the value's kind. * * @param kind The kind to compare against. * @returns True if the kind matches. */ isKind(kind: Kind): boolean; /** * Returns true if the haystack filter matches the value. * * @param filter The filter to test. * @param cx Optional haystack filter evaluation context. * @returns True if the filter matches ok. */ matches(filter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Dump the value to the local console output. * * @param message An optional message to display before the value. * @returns The value instance. */ inspect(message?: string): this; /** * Encodes to an encoded zinc value that can be used * in a haystack filter string. * * The encoding for a haystack filter is mostly zinc but contains * some exceptions. * * @returns The encoded value that can be used in a haystack filter. */ toFilter(): string; /** * Value equality check. * * @param value The value to test. * @returns True if the value is the same. */ equals(value: HStr): boolean; /** * Compares two values. * * @param value The value to compare against. * @returns The sort order as negative, 0, or positive */ compareTo(value: unknown): number; /** * @returns The object's value as a string. */ valueOf(): string; /** * @returns A string representation of the value. */ toString(): string; /** * Encode to zinc encoding. * * @returns The encoded zinc string. */ toZinc(): string; /** * @returns A JSON reprentation of the object. */ toJSON(): string; /** * @returns A string containing the JSON representation of the object. */ toJSONString(): string; /** * @returns A byte buffer that has an encoded JSON string representation of the object. */ toJSONUint8Array(): Uint8Array; /** * @returns A JSON v3 representation of the object. */ toJSONv3(): string; /** * @returns An Axon encoded string of the value. */ toAxon(): string; /** * @returns Returns the value instance. */ newCopy(): HStr; /** * @returns The value as a grid. */ toGrid(): HGrid; /** * @returns The value as a list. */ toList(): HList<HStr>; /** * @returns The value as a dict. */ toDict(): HDict; } /** * Haystack ref. */ declare class HRef implements HVal { #private; /** * Constructs a new haystack ref. * * @param value The value. * @param displayName The optional display name. */ private constructor(); /** * Makes a Haystack ref. * * @param value The value or hayson ref. * @param displayName Optional display string for a reference. * @returns A haystack ref. */ static make(value: string | HaysonRef | HRef | HStr, displayName?: string): HRef; /** * @returns The ref value. */ get value(): string; set value(value: string); /** * @returns The display name value in shorthand. */ get dis(): string; set dis(value: string); /** * @returns The display name value. */ get displayName(): string; set displayName(value: string); /** * @returns The value's kind. */ getKind(): Kind; /** * Compares the value's kind. * * @param kind The kind to compare against. * @returns True if the kind matches. */ isKind(kind: Kind): boolean; /** * Returns true if the haystack filter matches the value. * * @param filter The filter to test. * @param cx Optional haystack filter evaluation context. * @returns True if the filter matches ok. */ matches(filter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Dump the value to the local console output. * * @param message An optional message to display before the value. * @returns The value instance. */ inspect(message?: string): this; /** * Encodes to an encoded zinc value that can be used * in a haystack filter string. * * The encoding for a haystack filter is mostly zinc but contains * some exceptions. * * @returns The encoded value that can be used in a haystack filter. */ toFilter(): string; /** * Value equality check. * * @param value The value to test. * @returns True if the ref is the same. */ equals(value: unknown): boolean; /** * Compares two values. * * @param value The value to compare against. * @returns The sort order as negative, 0, or positive */ compareTo(value: unknown): number; /** * @returns A string representation of the value. */ toString(): string; /** * @returns The ref's value. */ valueOf(): string; /** * Encode to zinc encoding. * * @params excludeDis Excludes the display name from the encoding. * @returns The encoded zinc string. */ toZinc(excludeDis?: boolean): string; /** * @returns A JSON reprentation of the object. */ toJSON(): HaysonRef; /** * @returns A string containing the JSON representation of the object. */ toJSONString(): string; /** * @returns A byte buffer that has an encoded JSON string representation of the object. */ toJSONUint8Array(): Uint8Array; /** * @returns A JSON v3 representation of the object. */ toJSONv3(): JsonV3Ref; /** * @returns An Axon encoded string. */ toAxon(): string; /** * @returns Returns the value instance. */ newCopy(): HRef; /** * @returns A ref with no display name. */ noDis(): HRef; /** * @returns The value as a grid. */ toGrid(): HGrid; /** * @returns The value as a list. */ toList(): HList<HRef>; /** * @returns The value as a dict. */ toDict(): HDict; } interface PartialHaysonSymbol { _kind?: Kind; val: string; } /** * Haystack symbol. */ declare class HSymbol implements HVal { #private; /** * Constructs a new haystack symbol. * * @param value The value. */ private constructor(); /** * Makes a haystack symbol. * * @param value The value string or Hayson symbol object. * @returns A haystack symbol. */ static make(value: string | HaysonSymbol | HSymbol): HSymbol; /** * @returns The symbol value. */ get value(): string; set value(value: string); /** * @returns The value's kind. */ getKind(): Kind; /** * Compares the value's kind. * * @param kind The kind to compare against. * @returns True if the kind matches. */ isKind(kind: Kind): boolean; /** * Returns true if the haystack filter matches the value. * * @param filter The filter to test. * @param cx Optional haystack filter evaluation context. * @returns True if the filter matches ok. */ matches(filter: string | Node, cx?: Partial<EvalContext>): boolean; /** * Dump the value to the local console output. * * @param message An optional message to display before the value. * @returns The value instance. */ inspect(message?: string): this; /** * Encodes to an encoded zinc value that can be used * in a haystack filter string. * * The encoding for a haystack filter is mostly zinc but contains * some exceptions. * * @returns The encoded value that can be used in a haystack filter. */ toFilter(): string; /** * Value equality check. * * @param value The value to test. * @returns True if the value is the same. */ equals(value: unknown): boolean; /** * Compares two values. * * @param value The value to compare against. * @returns The sort order as negative, 0, or positive */ compareTo(value: unknown): number; /** * @returns A string representation of the value. */ toString(): string; /** * @returns A encoded reference. */ valueOf(): string; /** * Encode to zinc encoding. * * @returns The encoded zinc string. */ toZinc(): string; /** * @returns A JSON reprentation of the object. */ toJSON(): HaysonSymbol; /** * @returns A string containing the JSON representation of the object. */ toJSONString(): string; /** * @returns A byte buffer that has an encoded JSON string representation of the object. */ toJSONUint8Array(): Uint8Array; /** * @returns A JSON v3 representation of the object. */ toJSONv3(): JsonV3Symbol; /** * @returns An Axon encoded string of the value. */ toAxon(): string; /** * @returns Returns the value instance. */ newCopy(): HSymbol; /** * @returns The value as a grid. */ toGrid(): HGrid; /** * @returns The value as a list. */ toList(): HList<HSymbol>; /** * @returns The value as a dict. */ toDict(): HDict; } interface Defs { [prop: string]: HDict; } interface NameToDefs { [prop: string]: HDict[]; } /** * A unit dict. */ interface Unit extends HDict { quantity: HStr; name: HStr; symbol: HStr; } /** *