Last active
June 18, 2020 08:28
-
-
Save karol-majewski/cf1e95c7a7efb5c8d418794b204bc365 to your computer and use it in GitHub Desktop.
Interspersing collections in TypeScript
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
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