Last active
January 8, 2016 10:54
-
-
Save dimitrismistriotis/4c44c979037231b1602f to your computer and use it in GitHub Desktop.
getJoinedArrayText
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
/** | |
* 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