Created
July 3, 2022 18:55
-
-
Save arronhunt/32daf52b95c98be07565aa26d9c61c29 to your computer and use it in GitHub Desktop.
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
/** | |
* Truncate a list of names at return a human friendly sentence fragment. | |
* @param {string[]} list A list of name strings to format | |
* @param {number} max The maximum number of names to show before appending a count | |
* @example | |
* // returns "Abi, Jeri and Zoi" | |
* truncate(["Abi, Jeri, Zoi"]) | |
* @example | |
* // Returns "Abi and 2 others" | |
* truncate(["Abi, Jeri, Zoi"], 1) | |
*/ | |
function truncate(list, max = 3) { | |
// Safety | |
max = Math.max(1, max); | |
// Short circuit if there's only | |
// one item in the array. | |
if (list.length === 1) { | |
return list; | |
} | |
let gte = list.length - max; | |
let lte = max - list.length; | |
let parts = [ | |
list.slice(0, gte <= lte ? -1 : lte), | |
list.length > max ? [gte + " others"] : list.slice(-1) | |
]; | |
return [parts[0].join(", "), parts[1]].join(" and "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment