Write a function `omit(obj, keys)` that returns a new object without the specified keys.
Problem Statement
<p>Write a function <code>omit(obj, keys)</code> that returns a new object without the specified keys.</p>
Examples
Input: obj = { a: 1, b: 2, c: 3 }, keys = ["b"]
Output: { a: 1, c: 3 }
Explanation: Key "b" is omitted from the result.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Create a new object with all properties, then remove the specified keys.
š” Hint 2:
Or filter Object.entries() and reconstruct the object.
š” Hint 3:
const set = new Set(keys); return Object.fromEntries(Object.entries(obj).filter(([k]) => !set.has(k)));
Editorial & Approach
Problem Overview & Intuition
To solve Omit Properties from Object, we consider the execution characteristics of JavaScript engines. Write a function `omit(obj, keys)` that returns a new object without the specified keys. 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 (create a new object with all properties, then remove the specified keys).
- Implement Logic: Handle state and transformations efficiently (or filter object.entries() and reconstruct the object).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function omit(obj, keys) {
const set = new Set(keys);
return Object.fromEntries(Object.entries(obj).filter(([k]) => !set.has(k)));
}
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.