diff options
Diffstat (limited to 'src/utils')
-rw-r--r-- | src/utils/misc.tsx | 30 |
1 files changed, 29 insertions, 1 deletions
diff --git a/src/utils/misc.tsx b/src/utils/misc.tsx index aca7661..9d4c001 100644 --- a/src/utils/misc.tsx +++ b/src/utils/misc.tsx @@ -69,4 +69,32 @@ export function mergeDefaults<T>(obj: T, defaults: T): T { } } return obj; -}
\ No newline at end of file +} + + +/** + * Join an array of strings in a human readable way (1, 2 and 3) + * @param elements Elements + */ +export function humanFriendlyJoin(elements: string[]): string; +/** + * Join an array of strings in a human readable way (1, 2 and 3) + * @param elements Elements + * @param mapper Function that converts elements to a string + */ +export function humanFriendlyJoin<T>(elements: T[], mapper: (e: T) => string): string; +export function humanFriendlyJoin(elements: any[], mapper: (e: any) => string = s => s): string { + const { length } = elements; + if (length === 0) return ""; + if (length === 1) return mapper(elements[0]); + + let s = ""; + + for (let i = 0; i < length; i++) { + s += mapper(elements[i]); + if (length - i > 2) s += ", "; + else if (length - i > 1) s += " and "; + } + + return s; +} |