Skip to content

Commit

Permalink
Add grid find method
Browse files Browse the repository at this point in the history
  • Loading branch information
garethj2 committed Jan 6, 2025
1 parent f9b14d4 commit 656a015
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
21 changes: 21 additions & 0 deletions spec/core/HGrid.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1324,6 +1324,27 @@ type,val
})
}) // #any()

describe('#find()', function (): void {
it('returns the row dict for a match', function (): void {
expect(grid.find('foo')?.toJSON()).toEqual({ foo: 'foo' })
})

it('returns true for a match when using a node', function (): void {
const node = HFilter.parse('foo')
expect(grid.find(node)?.toJSON()).toEqual({ foo: 'foo' })
})

it('returns false when there is not a match', function (): void {
expect(grid.find('food')).toBeUndefined()
})

it('throws an error when the filter is invalid', function (): void {
expect((): void => {
grid.find('foo = true')
}).toThrow()
})
}) // #find()

describe('#matches()', function (): void {
it('returns true for a match', function (): void {
expect(grid.matches('foo')).toBe(true)
Expand Down
35 changes: 35 additions & 0 deletions src/core/HGrid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1282,6 +1282,41 @@ export class HGrid<DictVal extends HDict = HDict>
return result
}

/**
* 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.
*/
public find(
filter: string | Node,
cx?: Partial<EvalContext>
): DictVal | undefined {
let result: DictVal | undefined

this.runFilter(
filter,
(match: boolean, row: DictVal): boolean => {
if (match) {
result = row

// Stop iterating since we have one match.
return false
}

// Keep iterating.
return true
},
cx
)
return result
}

/**
* Returns true if the haystack filter matches the value.
*
Expand Down

0 comments on commit 656a015

Please sign in to comment.