From 70166467659e0b82629798288d1a7be80f6e4481 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Fri, 6 Nov 2026 19:48:47 +0530 Subject: [PATCH] feat: add string capitalize algorithm --- String/Capitalize.js | 20 ++++++++++++++++ String/test/Capitalize.test.js | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 String/Capitalize.js create mode 100644 String/test/Capitalize.test.js diff --git a/String/Capitalize.js b/String/Capitalize.js new file mode 100644 index 0000000000..7e684322a4 --- /dev/null +++ b/String/Capitalize.js @@ -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 } diff --git a/String/test/Capitalize.test.js b/String/test/Capitalize.test.js new file mode 100644 index 0000000000..0949cfdada --- /dev/null +++ b/String/test/Capitalize.test.js @@ -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) + }) +})