To Be Or Not To Be - Problem
Create a testing utility function called expect that mimics the behavior of popular testing frameworks like Jest or Chai. This function is the foundation of how developers write unit tests to verify their code works correctly.
Your task: Write an expect function that takes any value and returns an object with two assertion methods:
toBe(val)- Returnstrueif both values are strictly equal (===), otherwise throws an error with message "Not Equal"notToBe(val)- Returnstrueif both values are NOT strictly equal (!==), otherwise throws an error with message "Equal"
Example usage:
expect(5).toBe(5); // returns true
expect(5).notToBe(10); // returns true
expect(5).toBe(10); // throws "Not Equal"
expect(5).notToBe(5); // throws "Equal" Input & Output
example_1.js โ Successful toBe assertion
$
Input:
expect(5).toBe(5)
โบ
Output:
true
๐ก Note:
Both values are 5 and strictly equal (===), so toBe returns true
example_2.js โ Successful notToBe assertion
$
Input:
expect(5).notToBe(null)
โบ
Output:
true
๐ก Note:
5 and null are not equal (!==), so notToBe returns true
example_3.js โ Failed toBe assertion
$
Input:
expect(5).toBe(null)
โบ
Output:
Error: "Not Equal"
๐ก Note:
5 and null are not strictly equal, so toBe throws an error with message 'Not Equal'
Visualization
Tap to expand
Understanding the Visualization
1
Capture Expected Value
The expect function stores the value to be tested
2
Create Assertion Object
Return an object with toBe and notToBe methods
3
Perform Comparison
Methods compare stored value with provided argument
4
Return or Throw
Return true if assertion passes, throw error if it fails
Key Takeaway
๐ฏ Key Insight: Use closures to create a testing framework foundation that captures values and provides assertion methods with proper error handling
Time & Space Complexity
Time Complexity
O(1)
Each assertion operation takes constant time regardless of input size
โ Linear Growth
Space Complexity
O(1)
Only stores the expected value and creates a simple object with two methods
โ Linear Space
Constraints
-
The function must return an object with exactly two methods:
toBeandnotToBe -
Use strict equality (
===) and strict inequality (!==) for comparisons - Error messages must be exactly "Not Equal" and "Equal"
-
Methods should return
truewhen assertions pass
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code