Last active
February 6, 2022 19:20
-
-
Save codeBelt/9b61a3b203aad48a5fadedbefac40b21 to your computer and use it in GitHub Desktop.
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
// JavaScript Version | |
export const buildFirstMiddleLastList = (list) => { | |
const { 0: first, [list.length - 1]: last, ...rest } = list; | |
return [ | |
first, | |
Object.values(rest), | |
list.length > 1 ? last : undefined | |
]; | |
}; | |
const arrayData = ['a', 'b', 'c', 'd', 'e']; | |
const [first, middle, last] = buildFirstMiddleLastList(arrayData); | |
first; // "a" | |
middle; // ["b", "c", "d"] | |
last; // "e" |
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
// Jest Test | |
describe('buildFirstMiddleLastList()', () => { | |
test.each` | |
input | expected | |
${[]} | ${[undefined, [], undefined]} | |
${[1]} | ${[1, [], undefined]} | |
${[1, 2]} | ${[1, [], 2]} | |
${[1, 2, 3, 4, 5]} | ${[1, [2, 3, 4], 5]} | |
${['a', 'b', 'c', 'd', 'e']} | ${['a', ['b', 'c', 'd'], 'e']} | |
${[{ a: 'a' }, { b: 'b' }, { c: 'c' }]} | ${[{ a: 'a' }, [{ b: 'b' }], { c: 'c' }]} | |
`('returns $expected when buildFirstMiddleLastList($input)', ({ expected, input }) => { | |
expect(buildFirstMiddleLastList(input)).toEqual(expected); | |
}); | |
}); |
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
// TypeScript Version | |
type UnArray<T> = T extends Array<infer U> ? U : T; | |
type FirstMiddleLastListReturn<T> = [UnArray<T> | undefined, T, UnArray<T> | undefined]; | |
export const buildFirstMiddleLastList = <T extends any[]>(list: T): FirstMiddleLastListReturn<T> => { | |
const { 0: first, [list.length - 1]: last, ...rest } = list; | |
return [first, Object.values(rest) as T, list.length > 1 ? last : undefined]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment