Write a function `truncate(str, maxLength)` that truncates a string to maxLength and adds "..." if truncated.
Problem Statement
Examples
Input: str = "Hello World", maxLength = 5
Output: "Hello..."
Explanation: Truncated after 5 characters with ellipsis.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Truncate String, we consider the execution characteristics of JavaScript engines. Write a function `truncate(str, maxLength)` that truncates a string to maxLength and adds "..." if truncated. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (check if the string length exceeds maxlength).
- Implement Logic: Handle state and transformations efficiently (if it does, slice the string and append "...").
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function truncate(str, maxLength) {
return str.length > maxLength ? str.slice(0, maxLength) + "..." : str;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.