Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active June 18, 2020 08:28
Show Gist options
  • Save karol-majewski/cf1e95c7a7efb5c8d418794b204bc365 to your computer and use it in GitHub Desktop.
Save karol-majewski/cf1e95c7a7efb5c8d418794b204bc365 to your computer and use it in GitHub Desktop.
Interspersing collections in TypeScript
type NonEmptyArray<T> = [T, ...T[]];
const hasElements = <T>(collection: T[]): collection is NonEmptyArray<T> =>
collection.length > 0;
const head = <T>(collection: NonEmptyArray<T>): T =>
collection['0'];
const tail = <T>(collection: T[]): T[] => {
const [_, ...tail] = collection;
return tail;
}
const intersperse = <T, U>(collection: T[], separator: U): (T | U)[] => {
if (!hasElements(collection)) {
return [];
}
return (
tail(collection)
.reduce<(T | U)[]>(
(elements, element) =>
elements.concat([separator, element]),
[head(collection)],
)
);
};
console.log(
intersperse(['some', 'uri', 'fragment'], "-")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment