Skip to main content

colorGenerator


generateColor Function Overview

Definition

This code defines a TypeScript function named generateColor. The function takes a single letter as input and returns an HSL (Hue, Saturation, Lightness) color string based on the letter.


Code Example

export function generateColor(letter: string): string {
const hue = (letter.toLowerCase().charCodeAt(0) - 97) * 15;
return `hsl(${hue}, 70%, 50%)`;
}

Key Components

Export

info

The generateColor function is exported, allowing it to be reused in other parts of your project by importing it.


Function Parameters

  • Parameter: letter (Type: string)
  • Purpose: The function takes a single letter as input and generates a unique color based on its position in the alphabet.

Function Logic

1. Convert Letter to Lowercase

Explanation

The function converts the input letter to lowercase using letter.toLowerCase(). This ensures consistent behavior regardless of whether the input is uppercase or lowercase.


2. Get ASCII Code

How It Works

The charCodeAt(0) method retrieves the ASCII code of the first (and only) character of the input string. For example:

  • 'a'.charCodeAt(0) returns 97.
  • 'b'.charCodeAt(0) returns 98.

3. Calculate Hue

Formula

The hue is calculated with this formula:

(letter.toLowerCase().charCodeAt(0) - 97) * 15
  • letter.toLowerCase().charCodeAt(0): Gets the ASCII code of the lowercase letter.
  • Subtracting 97: Converts the ASCII code to a zero-based index (where 'a' = 0, 'b' = 1, etc.).
  • Multiplying by 15: Scales the index to produce a hue value for the HSL color model.

:::example Calculation Example For the letter 'b':

  1. 'b'.toLowerCase().charCodeAt(0) = 98
  2. 98 - 97 = 1 (zero-based index)
  3. 1 * 15 = 15 (hue) :::

4. Return HSL Color

Output

The function constructs and returns an HSL color string:

hsl(${hue}, 70%, 50%)
  • Hue: The calculated value based on the letter.
  • Saturation: Fixed at 70%.
  • Lightness: Fixed at 50%.

Usage Example

console.log(generateColor('a')); // Output: hsl(0, 70%, 50%)
console.log(generateColor('b')); // Output: hsl(15, 70%, 50%)
console.log(generateColor('z')); // Output: hsl(345, 70%, 50%)

Limitations

warning
  • The function does not handle non-alphabetical characters (e.g., @ or 1).
  • It assumes that the input will always be a single letter.

Enhancements

Suggestion

You can extend the function to handle edge cases (e.g., invalid inputs) or add support for non-alphabetical characters by implementing validation or fallback logic.