Skip to content

Commit

Permalink
adding first/toArray to Enumerable
Browse files Browse the repository at this point in the history
  • Loading branch information
lostfields committed Apr 8, 2020
1 parent 0a54645 commit 9b4b75d
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/linq/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ export interface IEnumerable<TEntity> extends Iterable<TEntity>, AsyncIterable<T
orderBy(property: keyof TEntity): this
orderBy(property: string): this
orderBy(): this

first(): TEntity | null
firstAsync(): Promise<TEntity | null>

toArray(): Array<TEntity>
toArrayAsync(): Promise<Array<TEntity>>
}

export default abstract class Base<TEntity extends any> implements IEnumerable<TEntity> {
Expand Down Expand Up @@ -72,6 +78,42 @@ export default abstract class Base<TEntity extends any> implements IEnumerable<T
return this
}

public first(): TEntity {
let result = this.getIterator().next()

if(result.done == false)
return result.value

return null
}

public async firstAsync(items?: Array<TEntity>): Promise<TEntity> {
let result = await this.getAsyncIterator().next()

if(result.done == false)
return result.value

return null
}

public toArray() {
let result: Array<TEntity> = []

for(let item of this.getIterator())
result.push(item)

return result
}

public async toArrayAsync() {
let result: Array<TEntity> = []

for await(let item of this.getAsyncIterator())
result.push(item)

return result
}

protected async * getAsyncIterator() {
if(!isAsyncIterable(this.items))
throw new TypeError('Enumerable is not async iterable')
Expand Down

0 comments on commit 9b4b75d

Please sign in to comment.