Skip to content

Commit

Permalink
Refactor access to default threshold
Browse files Browse the repository at this point in the history
- explicitely shows the option in the defaultConfig
- shortcircuit useless computations if it's not set
  • Loading branch information
romaricpascal committed Sep 27, 2022
1 parent 14b84af commit 5813b12
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/govuk/components/character-count/character-count.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ function CharacterCount ($module, config) {
return this
}

var defaultConfig = {
threshold: 0
}

// Read config set using dataset ('data-' values)
var datasetConfig = normaliseDataset($module.dataset)

Expand All @@ -42,6 +46,7 @@ function CharacterCount ($module, config) {
}

this.config = mergeConfigs(
defaultConfig,
config || {},
configOverrides,
datasetConfig
Expand Down Expand Up @@ -296,16 +301,19 @@ CharacterCount.prototype.getCountMessage = function () {
* (or no threshold is set)
*/
CharacterCount.prototype.isOverThreshold = function () {
// No threshold means we're always above threshold
// so we can save some computation
if (!this.config.threshold) {
return true
}

var $textarea = this.$textarea
var config = this.config

// Determine the remaining number of characters/words
var currentLength = this.count($textarea.value)
var maxLength = this.maxLength

// Set threshold if presented in config
var thresholdPercent = config.threshold ? config.threshold : 0
var thresholdValue = maxLength * thresholdPercent / 100
var thresholdValue = maxLength * this.config.threshold / 100

return (thresholdValue <= currentLength)
}
Expand Down

0 comments on commit 5813b12

Please sign in to comment.