Skip to content

Commit

Permalink
feat(iterables): add pairwise
Browse files Browse the repository at this point in the history
Add new pairwise function and tests.
  • Loading branch information
Daniel Bradley committed May 7, 2020
1 parent 81989ea commit d5c5967
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/iterables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,24 @@ export function* reverse<T>(source: Iterable<T>): Iterable<T> {
}
}

/**
* Returns an interable of each element in the input sequence and its predecessor,
* with the exception of the first element which is only returned as the predecessor of the second element.
* @param source The input collection
*/
export function* pairwise<T>(source: Iterable<T>): Iterable<[T, T]> {
let prev: T | undefined = undefined
let started = false
for (const item of source) {
if (!started) {
started = true
} else {
yield [prev!, item]
}
prev = item
}
}

/**
* Returns the sum of the values in the collection.
* @param source The input collection.
Expand Down
37 changes: 37 additions & 0 deletions test/iterable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,43 @@ describe('take', () => {
})
})

describe('pairwise', () => {
test('empty', () => {
expect(
pipe(Iterables.init({ count: 0 }))
.then(Iterables.pairwise)
.then(Iterables.toArray).result
).toEqual([])
})
test('single item', () => {
expect(
pipe(
(function* () {
yield 1
})()
)
.then(Iterables.pairwise)
.then(Iterables.toArray).result
).toEqual([])
})
test('multiple items', () => {
expect(
pipe(
(function* () {
yield 1
yield 2
yield 3
})()
)
.then(Iterables.pairwise)
.then(Iterables.toArray).result
).toEqual([
[1, 2],
[2, 3],
])
})
})

describe('length', () => {
it('can return zero length', () => {
expect(pipe(Iterables.init({ count: 0 })).then(Iterables.length).result).toEqual(0)
Expand Down

0 comments on commit d5c5967

Please sign in to comment.