String Transformer
Level: Advanced 60–90 minConcepts: 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
- Create a
StringTransformerthat takes an initial string - Support the following operations, all chainable:
capitalise()— capitalise the first letter of each wordreverse()— reverse the entire stringremoveWhitespace()— remove all whitespacesnakeCase()— convert to snake_casecamelCase()— convert to camelCasetruncate(n)— truncate to n characters, adding ”…” if truncatedrepeat(n)— repeat the string n times with a space separatorreplace(target, replacement)— replace all occurrences
result()returns the final transformed string- Operations are applied in order
Test Cases
| Input | Operations | Result |
|---|---|---|
| ”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