We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

To Be Or Not To Be

Number: 2813

Difficulty: Easy

Paid? No

Companies: Google, Microsoft, Amazon, Meta, Adobe


Problem Description

Implement a function expect that accepts any value and returns an object containing two methods: toBe and notToBe. The toBe method checks if the provided value is strictly equal (===) to the initial value and returns true if so; otherwise, it throws an error with the message "Not Equal". The notToBe method checks if the provided value is not strictly equal (!==) to the initial value and returns true if so; otherwise, it throws an error with the message "Equal".


Key Insights

  • The expect function should return an object with two methods: toBe and notToBe.
  • The toBe method compares using strict equality (===).
  • The notToBe method compares using strict inequality (!==).
  • If the comparisons do not meet the required condition, an error with a specific message should be thrown.
  • Edge cases include comparing differing types and null values.

Space and Time Complexity

Time Complexity: O(1) - Each function performs a constant-time comparison. Space Complexity: O(1) - No additional data structures are used.


Solution

The solution involves returning an object from the expect function that encapsulates two methods for assertions. Each method compares the stored initial value with the new value provided as an argument:

  1. The toBe method checks for strict equality. If the values are the same, it returns true; otherwise, it throws an error with "Not Equal".
  2. The notToBe method checks for strict inequality. If the values are not the same, it returns true; otherwise, it throws an error with "Equal".

This approach does not require any loops or additional space, ensuring constant runtime and space complexity.


Code Solutions

# Python implementation of expect function with two methods: toBe and notToBe

def expect(val):
    # Return an object with two methods
    return {
        'toBe': lambda other: True if val == other else (_ for _ in ()).throw(Exception("Not Equal")),
        'notToBe': lambda other: True if val != other else (_ for _ in ()).throw(Exception("Equal"))
    }

# Example usage:
# print(expect(5)['toBe'](5))  # Should print True
# print(expect(5)['notToBe'](None))  # Should print True
← Back to All Questions