String Transformer

Level: Advanced 60–90 min

Concepts: AlgorithmsDesign PatternsEdge CasesRefactoring


Build a string transformer that supports chainable operations. Each operation transforms the input string and passes the result to the next operation.

Requirements

  1. Create a StringTransformer that takes an initial string
  2. Support the following operations, all chainable:
    • capitalise() — capitalise the first letter of each word
    • reverse() — reverse the entire string
    • removeWhitespace() — remove all whitespace
    • snakeCase() — convert to snake_case
    • camelCase() — convert to camelCase
    • truncate(n) — truncate to n characters, adding ”…” if truncated
    • repeat(n) — repeat the string n times with a space separator
    • replace(target, replacement) — replace all occurrences
  3. result() returns the final transformed string
  4. Operations are applied in order

Test Cases

InputOperationsResult
”hello world”capitalise()“Hello World"
"hello world”reverse()“dlrow olleh"
"hello world”removeWhitespace()“helloworld"
"hello world”snakeCase()“hello_world"
"Hello World”camelCase()“helloWorld"
"hello world”truncate(5)“hello…"
"hello world”truncate(50)“hello world"
"ha”repeat(3)“ha ha ha"
"hello world”capitalise().reverse()“dlroW olleH"
"hello world”snakeCase().capitalise()“Hello_World"
""capitalise()""
"HELLO WORLD”camelCase()“helloWorld"
"hello-world test”snakeCase()“hello_world_test”

Bonus

  • Add cipher(n) — apply a Caesar cipher shifting each letter by n positions
  • Add slug() — convert to URL-friendly slug (lowercase, hyphens, no special characters)
  • Add mask(n) — mask all but the last n characters with asterisks (useful for credit cards, emails)
  • Make the transformer immutable — each operation returns a new transformer, allowing branching transformations