File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * @function countWords
3+ * @description Counts the number of words in a given string.
4+ * Words are separated by whitespace.
5+ * @param {string } str - The input string
6+ * @returns {number } - The number of words in the string
7+ * @see https://en.wikipedia.org/wiki/Word_count
8+ * @example countWords("Hello World") => 2
9+ * @example countWords(" Hello World ") => 2
10+ * @example countWords("") => 0
11+ */
12+ const countWords = ( str ) => {
13+ if ( typeof str !== 'string' ) {
14+ throw new TypeError ( 'Input must be a string' )
15+ }
16+ return str . trim ( ) === '' ? 0 : str . trim ( ) . split ( / \s + / ) . length
17+ }
18+
19+ export { countWords }
Original file line number Diff line number Diff line change 1+ import { countWords } from '../CountWords.js'
2+
3+ describe ( 'countWords' , ( ) => {
4+ test ( "countWords('Hello World') returns 2" , ( ) => {
5+ expect ( countWords ( 'Hello World' ) ) . toBe ( 2 )
6+ } )
7+
8+ test ( "countWords('') returns 0" , ( ) => {
9+ expect ( countWords ( '' ) ) . toBe ( 0 )
10+ } )
11+
12+ test ( "countWords(' Hello World ') returns 2" , ( ) => {
13+ expect ( countWords ( ' Hello World ' ) ) . toBe ( 2 )
14+ } )
15+
16+ test ( 'countWords single word returns 1' , ( ) => {
17+ expect ( countWords ( 'JavaScript' ) ) . toBe ( 1 )
18+ } )
19+
20+ test ( "countWords('The quick brown fox') returns 4" , ( ) => {
21+ expect ( countWords ( 'The quick brown fox' ) ) . toBe ( 4 )
22+ } )
23+
24+ test ( 'countWords with tabs and newlines' , ( ) => {
25+ expect ( countWords ( 'hello\tworld\nfoo' ) ) . toBe ( 3 )
26+ } )
27+
28+ test ( 'countWords with only spaces returns 0' , ( ) => {
29+ expect ( countWords ( ' ' ) ) . toBe ( 0 )
30+ } )
31+
32+ test ( 'throws TypeError for non-string input' , ( ) => {
33+ expect ( ( ) => countWords ( 123 ) ) . toThrow ( TypeError )
34+ } )
35+
36+ test ( 'throws TypeError for null input' , ( ) => {
37+ expect ( ( ) => countWords ( null ) ) . toThrow ( TypeError )
38+ } )
39+ } )
You can’t perform that action at this time.
0 commit comments