Turn an array into a comma-separated string with and or or at the end
This file contains 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