-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
052a755
commit 015ab39
Showing
1 changed file
with
20 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |