Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions String/Capitalize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @function capitalize
* @description Capitalizes the first letter of a string and
* lowercases the rest.
* @param {string} str - The input string
* @returns {string} - The capitalized string
* @see https://en.wikipedia.org/wiki/Capitalization
* @example capitalize("hello") => "Hello"
* @example capitalize("hELLO WORLD") => "Hello world"
* @example capitalize("") => ""
*/
const capitalize = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Input must be a string')
}
if (str.length === 0) return ''
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}

export { capitalize }
43 changes: 43 additions & 0 deletions String/test/Capitalize.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { capitalize } from '../Capitalize.js'

describe('capitalize', () => {
test("capitalize('hello') returns 'Hello'", () => {
expect(capitalize('hello')).toBe('Hello')
})

test("capitalize('hELLO WORLD') returns 'Hello world'", () => {
expect(capitalize('hELLO WORLD')).toBe('Hello world')
})

test("capitalize('') returns ''", () => {
expect(capitalize('')).toBe('')
})

test('capitalize single character', () => {
expect(capitalize('a')).toBe('A')
})

test('capitalize already capitalized string', () => {
expect(capitalize('Hello')).toBe('Hello')
})

test('capitalize all uppercase string', () => {
expect(capitalize('HELLO')).toBe('Hello')
})

test('capitalize string with numbers', () => {
expect(capitalize('1hello')).toBe('1hello')
})

test('capitalize string starting with space', () => {
expect(capitalize(' hello')).toBe(' hello')
})

test('throws TypeError for non-string input', () => {
expect(() => capitalize(123)).toThrow(TypeError)
})

test('throws TypeError for null input', () => {
expect(() => capitalize(null)).toThrow(TypeError)
})
})
Loading