Skip to content

Commit

Permalink
feat(arrays): 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 d5c5967 commit a21af9c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/arrays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,19 @@ export function reverse<T>(source: ReadonlyArray<T>): T[] {
return Array.from(source).reverse()
}

/**
* Returns an array of each element in the input collection 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: ReadonlyArray<T>): [T, T][] {
const pairs: [T, T][] = []
for (let index = 1; index < source.length; index++) {
pairs.push([source[index - 1], source[index]])
}
return pairs
}

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

describe('pairwise', () => {
test('empty', () => {
expect(Arrays.pairwise([])).toEqual([])
})
test('single item', () => {
expect(Arrays.pairwise([1])).toEqual([])
})
test('multiple items', () => {
expect(Arrays.pairwise([1, 2, 3])).toEqual([
[1, 2],
[2, 3],
])
})
})

describe('length', () => {
test('zero length', () => {
expect(Arrays.length([])).toEqual(0)
Expand Down

0 comments on commit a21af9c

Please sign in to comment.