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
To Be Or Not To Be - Testing Function INPUT expect(5).toBe(5) Value Breakdown: val = 5 arg = 5 Method Called: .toBe(5) Comparison: 5 === 5 Strict equality check ALGORITHM STEPS 1 Create expect(val) Factory returns object 2 Return methods toBe and notToBe 3 Call .toBe(5) Check val === arg 4 Evaluate result Return true or throw function expect (val) { return { toBe: (arg) => val === arg || throw "Not Equal" } FINAL RESULT true Why true? 5 === 5 evaluates to true Both type and value match No error thrown Error Case: expect(5).toBe(3) throws "Not Equal" Output: true Key Insight: Factory Function Pattern The expect() function uses the Factory Pattern to return an object with methods that have closure access to the original value. This enables method chaining like expect(val).toBe(arg) and allows clean, readable assertions similar to Jest or Chai testing frameworks. TutorialsPoint - To Be Or Not To Be | Factory Function Pattern
Asked in
Meta 35 Google 28 Microsoft 22 Amazon 18
28.6K 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