Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created November 27, 2021 15:45
Show Gist options
  • Save fostyfost/db9389aa4fd2885068edfceec5cba3cf to your computer and use it in GitHub Desktop.
Save fostyfost/db9389aa4fd2885068edfceec5cba3cf to your computer and use it in GitHub Desktop.
Array to sequence
import { toSequence } from './to-sequence'
test('`toSequence` should work correctly', () => {
expect(toSequence([])).toEqual([])
expect(toSequence(['a'])).toEqual([['a', undefined]])
expect(toSequence(['a', 'b'])).toEqual([['a', 'b']])
expect(toSequence(['a', 'b', 'c'])).toEqual([['a', 'b'], ['b', 'c']])
expect(toSequence(['a', 'b', 'c', 'd'])).toEqual([['a', 'b'], ['b', 'c'], ['c', 'd']])
expect(toSequence([{ id: 'a' }, { id: 'b'}, { id: 'c' }])).toEqual([
[{ id: 'a' }, { id: 'b' }],
[{ id: 'b' }, { id: 'c' }],
])
})
/**
* Takes an array of elements and returns an array, the elements of which are arrays of two values,
* where the first value indicates the previous value of the array or the first element of the passed array,
* and the second value indicates the current value of the loop or the value of the next element.
*
* Examples:
* toSequence(['a', 'b']) // -> [['a', 'b']]
* toSequence(['a', 'b', 'c]) // -> [['a', 'b'], ['b', 'c']]
*/
export const toSequence = <T = unknown>(items: T[]): [T | undefined, T | undefined][] => {
return items.reduce<[T, T][]>((acc, point, index, arr) => {
if (index !== 1) {
acc.push(index > 0 ? [arr[index - 1], point] : [point, arr[index + 1]])
}
return acc
}, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment