( value: string | number | null | undefined, maxLength: number, counterFormatter?: (inputLength: number, maxLength: number) => string )
| 1 | import { printIonError } from '@utils/logging'; |
| 2 | |
| 3 | export const getCounterText = ( |
| 4 | value: string | number | null | undefined, |
| 5 | maxLength: number, |
| 6 | counterFormatter?: (inputLength: number, maxLength: number) => string |
| 7 | ) => { |
| 8 | const valueLength = value == null ? 0 : value.toString().length; |
| 9 | const defaultCounterText = defaultCounterFormatter(valueLength, maxLength); |
| 10 | |
| 11 | /** |
| 12 | * If developers did not pass a custom formatter, |
| 13 | * use the default one. |
| 14 | */ |
| 15 | if (counterFormatter === undefined) { |
| 16 | return defaultCounterText; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Otherwise, try to use the custom formatter |
| 21 | * and fallback to the default formatter if |
| 22 | * there was an error. |
| 23 | */ |
| 24 | try { |
| 25 | return counterFormatter(valueLength, maxLength); |
| 26 | } catch (e) { |
| 27 | printIonError('[ion-input] - Exception in provided `counterFormatter`:', e); |
| 28 | return defaultCounterText; |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | const defaultCounterFormatter = (length: number, maxlength: number) => { |
| 33 | return `${length} / ${maxlength}`; |
no test coverage detected