Difficulty: Easy | Acceptance: 63.30% | Paid: No Topics: N/A
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.
toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error “Not Equal”.
notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error “Equal”.
- Examples
- Constraints
- Object Return Approach
- Class-based Approach
Examples
Example 1
Input:
func = () => expect(5).toBe(5)
Output:
{"value": true}
Explanation: 5 === 5 so this expression returns true.
Example 2
Input:
func = () => expect(5).toBe(null)
Output:
{"error": "Not Equal"}
Explanation: 5 !== null so this expression throw the error “Not Equal”.
Example 3
Input:
func = () => expect(5).notToBe(null)
Output:
{"value": true}
Explanation: 5 !== null so this expression returns true.
Constraints
val is a primitive value (string, number, boolean, null, undefined, symbol)
Object Return Approach
Intuition Return an object containing two methods that compare the original value with the passed value using strict equality operators.
Steps
- Create an expect function that takes a value
- Return an object with toBe and notToBe methods
- toBe checks strict equality (===) and throws “Not Equal” if false
- notToBe checks strict inequality (!==) and throws “Equal” if false
class Expect:
def __init__(self, val):
self.val = val
def toBe(self, other):
if self.val == other:
return True
raise Exception("Not Equal")
def notToBe(self, other):
if self.val != other:
return True
raise Exception("Equal")
def expect(val):
return Expect(val)Complexity
- Time: O(1)
- Space: O(1)
- Notes: Simple and direct approach with minimal overhead
Class-based Approach
Intuition Use a class to encapsulate the expected value and provide comparison methods as class methods.
Steps
- Define a class that stores the expected value
- Implement toBe and notToBe as instance methods
- Create and return an instance of this class from the expect function
class Expect:
def __init__(self, val):
self.val = val
def toBe(self, other):
if self.val is other or self.val == other:
return True
raise Exception("Not Equal")
def notToBe(self, other):
if self.val is not other and self.val != other:
return True
raise Exception("Equal")
def expect(val):
return Expect(val)Complexity
- Time: O(1)
- Space: O(1)
- Notes: More structured approach, useful for extending with additional methods