Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Last active February 6, 2022 19:20
Show Gist options
  • Save codeBelt/9b61a3b203aad48a5fadedbefac40b21 to your computer and use it in GitHub Desktop.
Save codeBelt/9b61a3b203aad48a5fadedbefac40b21 to your computer and use it in GitHub Desktop.
// 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"
// 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);
});
});
// 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