Class HGrid<DictVal>

A haystack grid.

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'))

Type Parameters

Implements

Indexable

  • [prop: number]: undefined | DictVal

    Numerical index access.

Constructors

  • Constructs a new grid.

    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' } },
    ])

    Type Parameters

    Parameters

    Returns HGrid<DictVal>

Accessors

  • get first(): undefined | DictVal
  • Return the first row in the grid or undefined if it can't be found.

    const dict = grid.first
    if (dict) {
    // Do something
    }

    Returns undefined | DictVal

    The dict or undefined if it does not exist.

  • get last(): undefined | DictVal
  • Return the last row in the grid or undefined if it can't be found.

    const dict = grid.last
    if (dict) {
    // Do something
    }

    Returns undefined | DictVal

    The dict or undefined if it does not exist.

  • get length(): number
  • // The number of rows in a grid.
    console.log(grid.length)

    Returns number

    The total number of rows.

Methods

  • Iterate over a grid using dicts for rows.

    This enables a 'for ... of' loop to be used directly on an iterator.

    Returns Iterator<DictVal>

    A new iterator for a grid.

    // 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]
  • Add a single or multiple rows using dicts.

    This method can be called in different ways to add multiple rows at a time.

    // 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' }])

    Parameters

    Returns this

    The grid instance.

    If the values being added are not dicts.

  • Add a column and return its new instance.

    If the column is already available then update it.

    grid.addColumn('Address', new HDict({ length: 30 }))
    

    Parameters

    • name: string

      The name of the column.

    • Optionalmeta: HDict

      The column's meta data.

    Returns GridColumn

    The new column or the one already found.

  • Return true if the filter matches at least one row.

    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.
    }

    Parameters

    • filter: string | Node

      The haystack filter or AST node.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns boolean

    true if there's at least one match

  • 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.

    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.
    }

    Parameters

    • name: string
    • innerFilter: string | Node
    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns boolean

    true if there's at least one match

  • Return true if the filter matches at least one row.

    if (grid.any('site')) {
    // The grid has some sites.
    }

    Parameters

    • filter: string | Node

      The haystack filter or AST node.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns boolean

    true if there's at least one match

  • 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.

    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'
    }

    Parameters

    • name: string
    • innerFilter: string | Node
    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns boolean

    true if there's at least one match

  • Return the sum of values for the specified column.

    If there are no numbers then Number.NaN is returned.

    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')

    Parameters

    • column: string | number | GridColumn

      The column name, column index or column instance.

    Returns number

    The average of all the numeric values.

  • // Create a grid with no rows (still retains column and meta).
    grid.clear()

    Clear all the rows from the grid.

    Returns void

  • Compares two grids.

    Parameters

    • value: unknown

      The value to compare against.

    Returns number

    The sort order as negative, 0, or positive.

  • Grid equality check.

    Parameters

    • value: unknown

      The value to test.

    Returns boolean

    True if the value is the same.

  • Filter the grid with the haystack filter and return a new grid with the results.

    // 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'))

    Parameters

    • filter: string | Node | (row: DictVal, index: number) => boolean

      The haystack filter, AST node or filter function callback.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns HGrid<DictVal>

    A new filtered grid.

  • 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.

    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"')

    Parameters

    • name: string

      The name of the column that holds the list values.

    • innerFilter: string | Node

      The haystack filter to run against the list.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns HGrid<DictVal>

    A filtered grid.

  • Return the first row dict that matches the filter or undefined if nothing is found.

    const dict = grid.find('site'))
    

    Parameters

    • filter: string | Node

      The haystack filter or AST node.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns undefined | DictVal

    The first row dict that matches the filter.

  • Return a row or undefined if it can't find it via its row number.

    // 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
    }

    Parameters

    • index: number

      The index number of the row.

    Returns undefined | DictVal

    The dict or undefined if it does not exist.

  • Returns a grid column via its name or index number. If it can't be found then return undefined.

    // 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
    }

    Parameters

    • index: string | number

      The column index number or name.

    Returns undefined | GridColumn

    The column or undefined if not found.

  • Return the column names (not display names).

    Returns string[]

    The column names.

  • Returns the number of columns.

    console.log('The table has this many columns: ' + grid.getColumnsLength())
    

    Returns number

    The number of columns.

  • const err = grid.getError()
    if (err) {
    // Do something with the error.
    }

    Returns undefined | { dis: string; trace: string; type: string }

    Error information or undefined if not available.

  • Does the grid have the specified column?

    if (grid.hasColumn('Address)) {
    // The grid has a column called address.
    }

    Parameters

    • name: string

      The name of the column.

    Returns boolean

    True if the grid has the column.

  • Insert rows as dicts at the specified index.

    // 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' }])

    Parameters

    Returns this

    The grid instance.

    An error if the index is invalid or the rows are not dicts.

  • Dump the value to the local console output.

    Parameters

    • Optionalmessage: string

      An optional message to display before the value.

    Returns this

    The value instance.

  • if (grid.isEmpty()) {
    // Grid is empty.
    }

    Returns boolean

    true if the grid is empty.

  • if (grid.isError()) {
    // Do something.
    }

    Returns boolean

    true if the grid has an error associated with it.

  • 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.

    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')

    Type Parameters

    Parameters

    • column: string | number | GridColumn

      The column name, column index or instance to create the list from.

    Returns HList<Value>

  • A mapping function that maps from an array of dicts into something else.

    // Map each row to a div using React...
    grid.map((dict: HDict) => <div>{dict.toZinc()}</div>>)

    Type Parameters

    • U

    Parameters

    • callback: (row: DictVal, index: number) => U

      A mapping callback that takes a row dict, an index number and returns a new value.

    Returns U[]

  • Returns true if the haystack filter matches the value.

    This is the same as the any method.

    if (grid.matches('site')) {
    // The grid has some sites.
    }

    Parameters

    • filter: string | Node

      The filter to test.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns boolean

    True if the filter matches ok.

  • Return the maximum value in the specified column.

    If there are no numbers then Number.MIN_SAFE_INTEGER is returned.

    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')

    Parameters

    • column: string | number | GridColumn

      The column name, column index or column instance.

    Returns number

    The maximum numerical value found.

  • Return the minimum of value in the specified column.

    If there are no numbers then Number.MAX_SAFE_INTEGER is returned.

    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')

    Parameters

    • column: string | number | GridColumn

      The column name, column index or column instance.

    Returns number

    The minimum numerical value found.

  • Selects a range from the grid.

    The start and end can be used to specify a range...

    // 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...

    // select the first 4 rows - [0, 1, 2, 4]...
    grid.filter('site').range(4).inspect()

    Parameters

    • startOrQuantity: number

      The start of the range or quantity.

    • Optionalend: number

      Optional end range.

    Returns this

    This grid instance.

  • Reduce the rows in a grid.

    // 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 }] }))

    Type Parameters

    Parameters

    • callback: (prev: U, current: DictVal, currentIndex: number, array: DictVal[]) => U

      The reducer callback. This method will be called with the previous and current rows (dicts) as well as the index number.

    • OptionalinitialValue: U

      Optional initial value for the reduce.

    Returns U

  • Remove the row from the grid via its index number of a haystack filter.

    // Remove a row via its index
    grid.remove(0)

    // Remove multiple rows via a Haystack Filter
    grid.remove('foo == "baa"')

    Parameters

    • filter: string | number | Node

      A haystack filter, index number or AST node.

    • Optionalcx: Partial<EvalContext>

      Optional haystack filter evaluation context.

    Returns DictVal[]

    The rows that were removed. If no rows were removed then the is empty.

  • Reorder the columns with the specified new order of names.

    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' ])

    Parameters

    • names: string | string[]

      The new order of column names to use.

    Returns void

  • Reverses the order of all the rows in the grid.

    // Sort the grid in descending order by foo
    grid.sortBy('foo').reverse()

    Returns void

  • Set the values or dict for an individual row.

    // 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' })

    Parameters

    • index: number

      The index number of the row.

    • values: HaysonDict | DictVal

      The dict or Hayson Dict.

    Returns this

    The grid instance.

    An error if the index is invalid or the number of rows incorrect.

  • Set the column at the specified index number.

    // Set the column at the specified index with the new name and length.
    grid.setColumn(3, 'Address', new HDict({ length: 30 }))

    Parameters

    • index: number

      The zero based index number of the column.

    • name: string

      The name of the column.

    • Optionalmeta: HDict

      Optional column's meta data.

    Returns GridColumn

    The updated column.

    An error if index does not exist in the columns.

  • 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.

    // 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'])

    Parameters

    • names: string | string[]

      The name of the column to sort by.

    Returns this

    The grid instance.

  • Return the sum of values for the specified column.

    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')

    Parameters

    • column: string | number | GridColumn

      The column name, column index or column instance.

    Returns number

    The sum of all the numeric values.

  • 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 string

    The encoded value that can be used in a haystack filter.

  • Encodes to an encoding zinc value.

    Parameters

    • Optionalnested: boolean

      An optional flag used to indiciate whether the value being encoded is nested.

    Returns string

    The encoded zinc string.

  • Provide a grid with unique values in the specified columns.

    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')

    Parameters

    • names: string | string[]

      The column names.

    Returns HGrid<DictVal>

    The filtered grid instance.