Explorer
JavaScript

Write a function `truncate(str, maxLength)` that truncates a string to maxLength and adds "..." if truncated.

Problem Statement

<p>Write a function <code>truncate(str, maxLength)</code> that truncates a string to maxLength and adds "..." if truncated.</p>

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

šŸ’” Hint 1: Check if the string length exceeds maxLength. šŸ’” Hint 2: If it does, slice the string and append "...". šŸ’” Hint 3: return str.length > maxLength ? str.slice(0, maxLength) + "..." : str;

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (check if the string length exceeds maxlength).
  3. Implement Logic: Handle state and transformations efficiently (if it does, slice the string and append "...").
  4. 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

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

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.

Truncate String

Easy

Write a function truncate(str, maxLength) that truncates a string to maxLength and adds "..." if truncated.

Example Scenarios
1Example 1
Input: str = "Hello World", maxLength = 5
Output: "Hello..."
Explanation:

Truncated after 5 characters with ellipsis.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["Hello...","Hi","Java..."]