From be59b357a91d38165ade285d783517be3edea131 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Tue, 3 Nov 2026 10:31:10 +0530 Subject: [PATCH] feat: add title case algorithm --- String/TitleCase.js | 23 +++++++++++++++++++++ String/test/TitleCase.test.js | 39 +++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 String/TitleCase.js create mode 100644 String/test/TitleCase.test.js diff --git a/String/TitleCase.js b/String/TitleCase.js new file mode 100644 index 0000000000..aeb74ca2ce --- /dev/null +++ b/String/TitleCase.js @@ -0,0 +1,23 @@ +/** + * @function titleCase + * @description Converts a string to title case where the first letter + * of each word is capitalized and the rest are lowercase. + * @param {string} str - The input string + * @returns {string} - The title cased string + * @see https://en.wikipedia.org/wiki/Title_case + * @example titleCase("hello world") => "Hello World" + * @example titleCase("the quick brown fox") => "The Quick Brown Fox" + * @example titleCase("HELLO WORLD") => "Hello World" + */ +const titleCase = (str) => { + if (typeof str !== 'string') { + throw new TypeError('Input must be a string') + } + return str + .toLowerCase() + .split(' ') + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' ') +} + +export { titleCase } diff --git a/String/test/TitleCase.test.js b/String/test/TitleCase.test.js new file mode 100644 index 0000000000..d35d3190ea --- /dev/null +++ b/String/test/TitleCase.test.js @@ -0,0 +1,39 @@ +import { titleCase } from '../TitleCase.js' + +describe('titleCase', () => { + test("titleCase('hello world') returns 'Hello World'", () => { + expect(titleCase('hello world')).toBe('Hello World') + }) + + test("titleCase('the quick brown fox') returns 'The Quick Brown Fox'", () => { + expect(titleCase('the quick brown fox')).toBe('The Quick Brown Fox') + }) + + test("titleCase('HELLO WORLD') returns 'Hello World'", () => { + expect(titleCase('HELLO WORLD')).toBe('Hello World') + }) + + test("titleCase('') returns ''", () => { + expect(titleCase('')).toBe('') + }) + + test('titleCase single word', () => { + expect(titleCase('javascript')).toBe('Javascript') + }) + + test('titleCase handles multiple spaces', () => { + expect(titleCase('hello world')).toBe('Hello World') + }) + + test('titleCase handles mixed case', () => { + expect(titleCase('hElLo WoRlD')).toBe('Hello World') + }) + + test('throws TypeError for non-string input', () => { + expect(() => titleCase(123)).toThrow(TypeError) + }) + + test('throws TypeError for null', () => { + expect(() => titleCase(null)).toThrow(TypeError) + }) +})