Skip to content

Commit

Permalink
feat: Iterable2.some, every, support AbortablePredicate
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillgroshkov committed Dec 27, 2023
1 parent 752d2b2 commit 9f3249b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/iter/iterable2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ test('iterable2', () => {
expect(_rangeIt(3).toArray()).toEqual([0, 1, 2])

expect(_rangeIt(1, 4).find(v => v % 2 === 0)).toBe(2)
expect(_rangeIt(1, 4).some(v => v % 2 === 0)).toBe(true)
expect(_rangeIt(1, 4).some(v => v % 2 === -1)).toBe(false)
expect(_rangeIt(1, 4).every(v => v % 2 === 0)).toBe(false)
expect(_rangeIt(1, 4).every(v => v > 0)).toBe(true)

expect(
_rangeIt(1, 4)
Expand Down
22 changes: 19 additions & 3 deletions src/iter/iterable2.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AbortableMapper, AbortablePredicate, END, Predicate, SKIP } from '../types'
import { AbortableMapper, AbortablePredicate, END, SKIP } from '../types'

/**
* Iterable2 is a wrapper around Iterable that implements "Iterator Helpers proposal":
Expand Down Expand Up @@ -34,10 +34,26 @@ export class Iterable2<T> implements Iterable<T> {
}
}

find(cb: Predicate<T>): T | undefined {
some(cb: AbortablePredicate<T>): boolean {
// eslint-disable-next-line unicorn/prefer-array-some
return !!this.find(cb)
}

every(cb: AbortablePredicate<T>): boolean {
let i = 0
for (const v of this.it) {
const r = cb(v, i++)
if (r === END || !r) return false
}
return true
}

find(cb: AbortablePredicate<T>): T | undefined {
let i = 0
for (const v of this.it) {
if (cb(v, i++)) return v
const r = cb(v, i++)
if (r === END) return
if (r) return v
}
}

Expand Down

0 comments on commit 9f3249b

Please sign in to comment.