Skip to content

Commit be59b35

Browse files
feat: add title case algorithm
1 parent 5c39e87 commit be59b35

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

‎String/TitleCase.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @function titleCase
3+
* @description Converts a string to title case where the first letter
4+
* of each word is capitalized and the rest are lowercase.
5+
* @param {string} str - The input string
6+
* @returns {string} - The title cased string
7+
* @see https://en.wikipedia.org/wiki/Title_case
8+
* @example titleCase("hello world") => "Hello World"
9+
* @example titleCase("the quick brown fox") => "The Quick Brown Fox"
10+
* @example titleCase("HELLO WORLD") => "Hello World"
11+
*/
12+
const titleCase = (str) => {
13+
if (typeof str !== 'string') {
14+
throw new TypeError('Input must be a string')
15+
}
16+
return str
17+
.toLowerCase()
18+
.split(' ')
19+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
20+
.join(' ')
21+
}
22+
23+
export { titleCase }

‎String/test/TitleCase.test.js‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { titleCase } from '../TitleCase.js'
2+
3+
describe('titleCase', () => {
4+
test("titleCase('hello world') returns 'Hello World'", () => {
5+
expect(titleCase('hello world')).toBe('Hello World')
6+
})
7+
8+
test("titleCase('the quick brown fox') returns 'The Quick Brown Fox'", () => {
9+
expect(titleCase('the quick brown fox')).toBe('The Quick Brown Fox')
10+
})
11+
12+
test("titleCase('HELLO WORLD') returns 'Hello World'", () => {
13+
expect(titleCase('HELLO WORLD')).toBe('Hello World')
14+
})
15+
16+
test("titleCase('') returns ''", () => {
17+
expect(titleCase('')).toBe('')
18+
})
19+
20+
test('titleCase single word', () => {
21+
expect(titleCase('javascript')).toBe('Javascript')
22+
})
23+
24+
test('titleCase handles multiple spaces', () => {
25+
expect(titleCase('hello world')).toBe('Hello World')
26+
})
27+
28+
test('titleCase handles mixed case', () => {
29+
expect(titleCase('hElLo WoRlD')).toBe('Hello World')
30+
})
31+
32+
test('throws TypeError for non-string input', () => {
33+
expect(() => titleCase(123)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for null', () => {
37+
expect(() => titleCase(null)).toThrow(TypeError)
38+
})
39+
})

0 commit comments

Comments
 (0)