Created
November 27, 2021 15:45
-
-
Save fostyfost/db9389aa4fd2885068edfceec5cba3cf to your computer and use it in GitHub Desktop.
Array to sequence
This file contains hidden or 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
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' }], | |
]) | |
}) |
This file contains hidden or 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
/** | |
* 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