@@ -211,20 +211,11 @@ export class CharacterCount extends ConfigurableComponent {
211211 * @param {string } [text] - Deprecated
212212 */
213213 updateCount ( text ) {
214- const { $textarea } = this
215- const { countType } = this . config
214+ const { $textarea, countFunctions } = this
215+ const { countType = 'length' } = this . config
216216
217- text = text ?? $textarea . value
218-
219- if ( countType === 'words' ) {
220- const tokens = text . match ( / \S + / g) ?? [ ] // Matches consecutive non-whitespace chars
221- this . length = tokens . length
222- return
223- }
224-
225- this . length = this . segmenter
226- ? Array . from ( this . segmenter . segment ( text ) ) . length
227- : text . length
217+ text ??= $textarea . value
218+ this . length = countFunctions [ countType ] . call ( this , text )
228219 }
229220
230221 /**
@@ -447,6 +438,30 @@ export class CharacterCount extends ConfigurableComponent {
447438 }
448439 }
449440
441+ /**
442+ * Character count functions
443+ *
444+ * @constant
445+ * @satisfies {Record<string, (this: CharacterCount, text: string) => number> }
446+ */
447+ countFunctions = Object . freeze ( {
448+ length ( text ) {
449+ return text . length
450+ } ,
451+ characters ( text ) {
452+ if ( ! this . segmenter ) {
453+ return text . length
454+ }
455+
456+ const segments = Array . from ( this . segmenter . segment ( text ) )
457+ return segments . length
458+ } ,
459+ words ( text ) {
460+ const tokens = text . match ( / \S + / g) ?? [ ] // Matches consecutive non-whitespace chars
461+ return tokens . length
462+ }
463+ } )
464+
450465 /**
451466 * Name for the component used when initialising using data-module attributes
452467 */
@@ -548,7 +563,7 @@ export function initCharacterCounts(options) {
548563 * @property {number } [maxwords] - Deprecated. Use `maxlength` and `countType: "words"` instead.
549564 * @property {number } [threshold=0] - The percentage value of the limit at which point the count message is displayed.
550565 * If this attribute is set, the count message will be hidden by default.
551- * @property {'characters' | 'words' } [countType] - The count type (`"characters"` or `"words"`) used to count the text.
566+ * @property {'length' | ' characters' | 'words' } [countType] - The count type (`"characters"` or `"words"`) used to count the text.
552567 * @property {string } textareaDescriptionClass - Textarea description class
553568 * @property {string } visibleCountMessageClass - Visible count message class
554569 * @property {string } screenReaderCountMessageClass - Screen reader count message class
0 commit comments