Skip to content

Commit 3a12a75

Browse files
Expose character count countFunctions
1 parent 3bdf52e commit 3a12a75

1 file changed

Lines changed: 27 additions & 12 deletions

File tree

packages/nhsuk-frontend/src/nhsuk/components/character-count/character-count.mjs

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -211,20 +211,11 @@ export class CharacterCount extends ConfigurableComponent {
211211
* @param {string} [text] - Deprecated
212212
*/
213213
updateCount(text) {
214-
const { $textarea } = this
214+
const { $textarea, countFunctions } = this
215215
const { countType } = 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, CharacterCountConfig['countFunction']>}
446+
*/
447+
countFunctions = Object.freeze({
448+
characters(text) {
449+
return text.length
450+
},
451+
graphemes(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
*/

0 commit comments

Comments
 (0)