To Be Or Not To Be - Problem

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".

This is similar to Jest or Chai assertion libraries used in JavaScript testing frameworks.

Input & Output

Example 1 — toBe Success
$ Input: expect(5).toBe(5)
Output: true
💡 Note: Since 5 === 5, the toBe method returns true without throwing an error
Example 2 — toBe Failure
$ Input: expect(5).toBe(null)
Output: throws "Not Equal"
💡 Note: Since 5 !== null, the toBe method throws an error with message "Not Equal"
Example 3 — notToBe Success
$ Input: expect(5).notToBe(null)
Output: true
💡 Note: Since 5 !== null, the notToBe method returns true without throwing an error

Constraints

  • val can be any JavaScript value (primitive or object)
  • toBe and notToBe methods should use strict equality (=== and !==)
  • Error messages must be exactly "Not Equal" and "Equal"

Visualization

Tap to expand
Test Assertion Framework: expect(5)expectvalue: 5Input FunctiontoBe(5) → true5 === 5 ✓toBe(null) → throws5 !== null ✗notToBe(null) → true5 !== null ✓AssertionObjectMethodsReturned Object🎯 Key Insight: Closures capture values for later assertion testing
Understanding the Visualization
1
Input
expect(5) receives value to test against
2
Process
Returns object with toBe/notToBe assertion methods
3
Usage
Methods compare values and return true or throw errors
Key Takeaway
🎯 Key Insight: Use closures to preserve the original value and return methods that can perform assertions against it
Asked in
Meta 35 Google 28 Microsoft 22 Amazon 18
28.5K 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