Created
May 2, 2022 13:03
-
-
Save jasonbyrne/372f0af7266ac40b12d45bfa9101f4a1 to your computer and use it in GitHub Desktop.
Turn an array into a comma-separated string with and or or at the end
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
export const humanReadableList = ( | |
array: unknown[], | |
join: ',' | ';' = ',', | |
finalJoin = 'and', | |
): string => { | |
if (!Array.isArray(array) || array.length == 0) return ''; | |
if (array.length == 1) return String(array[0]); | |
const arr = array.slice(0), | |
last = arr.pop(); | |
return array.length > 2 | |
? arr.join(`${join} `) + `${join} ${finalJoin} ${last}` | |
: `${array[0]} ${finalJoin} ${last}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment