Skip to content

Commit

Permalink
improve searchIterable
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 15, 2024
1 parent 052a755 commit 015ab39
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions src/iterable/searchIterable.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
import { toIterable, type ToIterableItem } from 'radashi'
import { castIterable, isArray, type CastIterableItem } from 'radashi'

export function searchIterable<T extends object>(
iterable: T,
match: (item: ToIterableItem<T>, index: number) => boolean,
): ToIterableItem<T> | undefined {
let index = 0
for (const item of toIterable(iterable)) {
if (match(item, index++)) {
return item
match: (item: CastIterableItem<T>, index: number) => boolean,
): CastIterableItem<T> | undefined {
let item: CastIterableItem<T> | undefined
if (isArray(iterable)) {
// Note: We can't use Array.prototype.find here, because it
// doesn't respect the sparseness of an array.
;(iterable as any[]).some((it, i) => {
if (match(it, i)) {
item = it
return true
}
})
} else {
let index = 0
for (item of castIterable(iterable)) {
if (match(item, index++)) {
break
}
}
}
return item
}

0 comments on commit 015ab39

Please sign in to comment.