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) - Returns true if both values are strictly equal (===), otherwise throws an error with message "Not Equal"
  • notToBe(val) - Returns true if 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
expect(5)Captures valueAssertion ObjecttoBe()notToBe()5 === 5โœ“ true5 === 10โœ— ErrorMethod calls๐Ÿ’กKey Insight: Closures capture the expected value,allowing methods to access it for comparison
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only stores the expected value and creates a simple object with two methods

n
2n
โœ“ Linear Space

Constraints

  • The function must return an object with exactly two methods: toBe and notToBe
  • Use strict equality (===) and strict inequality (!==) for comparisons
  • Error messages must be exactly "Not Equal" and "Equal"
  • Methods should return true when assertions pass
Asked in
Meta 25 Google 18 Netflix 15 Microsoft 12
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen