w3resource

TypeScript utility functions example

TypeScript Classes and OOP : Exercise-24 with Solution

Write a TypeScript utility class with static methods for common utility functions, such as formatDate, generateRandomString, and capitalizeString. Each method should provide the respective utility functionality and be accessible without creating an instance of the class. Test the utility class by using its static methods to perform various tasks.

Sample Solution:

TypeScript Code:

class Utility {
  static formatDate(date: Date): string {
    const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Intl.DateTimeFormat('en-US', options).format(date);
  }

  static generateRandomString(length: number): string {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      result += characters.charAt(randomIndex);
    }
    return result;
  }

  static capitalizeString(input: string): string {
    return input.charAt(0).toUpperCase() + input.slice(1);
  }
}

// Testing the Utility class
const today = new Date();
console.log(`Formatted Date: ${Utility.formatDate(today)}`);

const randomString = Utility.generateRandomString(10);
console.log(`Random String: ${randomString}`);

const inputString = 'hello world';
console.log(`Capitalized String: ${Utility.capitalizeString(inputString)}`);

Explanations:

In the exercise above -

  • First, define a "Utility" class with static methods for "formatDate()", "generateRandomString()", and "capitalizeString()".
  • The "formatDate()" method formats a given 'Date' object into a human-readable date string.
  • The "generateRandomString()" method generates a random string of a specified length using alphanumeric characters.
  • The "capitalizeString()" method capitalizes the first letter of a string.
  • Finally test the "Utility" class by calling each static method with appropriate parameters and displaying the results.

Output:

"Formatted Date: October 9, 2023" 
"Random String: AZ9uUMw7vq" 
"Capitalized String: Hello world"

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Singleton design pattern example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.