Skip to content

Instantly share code, notes, and snippets.

@dimitrismistriotis
Last active January 8, 2016 10:54
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 dimitrismistriotis/4c44c979037231b1602f to your computer and use it in GitHub Desktop.
Save dimitrismistriotis/4c44c979037231b1602f to your computer and use it in GitHub Desktop.
getJoinedArrayText
/**
* Returns array join in a more natural language style by adding commas and
* having the last item prefixed with "and".
* Examples:
*
* getJoinedArrayText(['1'])
* "1"
* getJoinedArrayText(['1', '2'])
* "1 and 2"
* getJoinedArrayText(['1', '2', '3'])
* "1, 2 and 3"
* getJoinedArrayText(['1', '2', '3', '4'])
* "1, 2, 3 and 4"
* getJoinedArrayText([1,2,3,4,5,6])
* "6 selected items"
* getJoinedArrayText([1,2,3,4,5,6], 'items')
* "6 items"
*/
function getJoinedArrayText(arrayToJoin, manyItemsText) {
const DISPLAY_LENGTH_TIPPING_POINT = 5;
var joinedArray = "", arrayLength = arrayToJoin.length;
if (arrayLength <= DISPLAY_LENGTH_TIPPING_POINT) {
return arrayToJoin.slice(0, arrayLength - 1).join(', ') +
(arrayLength > 1 ? " and " : '') +
arrayToJoin[arrayLength - 1];
} else {
return arrayLength + ' ' + ((manyItemsText == null) ? ' selected items' : manyItemsText.trim());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment