Skip to content

Instantly share code, notes, and snippets.

@jasonbyrne
Created May 2, 2022 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbyrne/372f0af7266ac40b12d45bfa9101f4a1 to your computer and use it in GitHub Desktop.
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
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