Passed
Push — feature/application-translatio... ( 96b410...facbc9 )
by Tristan
06:59
created

resources/assets/js/components/WordCounter/helpers.ts   A

Complexity

Total Complexity 5
Complexity/F 0

Size

Lines of Code 30
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 22
c 0
b 0
f 0
dl 0
loc 30
rs 10
mnd 5
bc 5
fnc 0
bpm 0
cpm 0
noi 0
1
export const countNumberOfWords = (innerText: string): number => {
2
  if (innerText && innerText.trim()) {
3
    return innerText.replace(/\s+/g, " ").trim().split(" ").length;
4
  }
5
  return 0;
6
};
7
8
export const stringEndsInWhitespace = (value: string): boolean => {
9
  const pattern = /.*\s$/; // \s represents any whitespace characters, like tabs, spaces and newlines
10
  return pattern.test(value);
11
};
12
13
export const truncateWords = (value: string, wordLimit: number): string => {
14
  const wordCount = countNumberOfWords(value);
15
16
  if (wordCount === wordLimit && stringEndsInWhitespace(value)) {
17
    return `${value.trim()} `;
18
  }
19
20
  if (wordCount > wordLimit) {
21
    // This pattern finds the first n words, where words are characters divided by whitespace, and n=wordLimit
22
    const pattern = new RegExp(`([^\\s]+\\s+){${wordLimit}}`, "g");
23
    const matches = pattern.exec(value);
24
    if (matches) {
25
      return `${matches[0].trim()} `;
26
    }
27
  }
28
  return value;
29
};
30