Skip to content

Commit 7016646

Browse files
feat: add string capitalize algorithm
1 parent 5c39e87 commit 7016646

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

‎String/Capitalize.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @function capitalize
3+
* @description Capitalizes the first letter of a string and
4+
* lowercases the rest.
5+
* @param {string} str - The input string
6+
* @returns {string} - The capitalized string
7+
* @see https://en.wikipedia.org/wiki/Capitalization
8+
* @example capitalize("hello") => "Hello"
9+
* @example capitalize("hELLO WORLD") => "Hello world"
10+
* @example capitalize("") => ""
11+
*/
12+
const capitalize = (str) => {
13+
if (typeof str !== 'string') {
14+
throw new TypeError('Input must be a string')
15+
}
16+
if (str.length === 0) return ''
17+
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
18+
}
19+
20+
export { capitalize }

‎String/test/Capitalize.test.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { capitalize } from '../Capitalize.js'
2+
3+
describe('capitalize', () => {
4+
test("capitalize('hello') returns 'Hello'", () => {
5+
expect(capitalize('hello')).toBe('Hello')
6+
})
7+
8+
test("capitalize('hELLO WORLD') returns 'Hello world'", () => {
9+
expect(capitalize('hELLO WORLD')).toBe('Hello world')
10+
})
11+
12+
test("capitalize('') returns ''", () => {
13+
expect(capitalize('')).toBe('')
14+
})
15+
16+
test('capitalize single character', () => {
17+
expect(capitalize('a')).toBe('A')
18+
})
19+
20+
test('capitalize already capitalized string', () => {
21+
expect(capitalize('Hello')).toBe('Hello')
22+
})
23+
24+
test('capitalize all uppercase string', () => {
25+
expect(capitalize('HELLO')).toBe('Hello')
26+
})
27+
28+
test('capitalize string with numbers', () => {
29+
expect(capitalize('1hello')).toBe('1hello')
30+
})
31+
32+
test('capitalize string starting with space', () => {
33+
expect(capitalize(' hello')).toBe(' hello')
34+
})
35+
36+
test('throws TypeError for non-string input', () => {
37+
expect(() => capitalize(123)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for null input', () => {
41+
expect(() => capitalize(null)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)