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

Examples

Example 1

1
2
3
Input: func = () => expect(5).toBe(5)
Output: {"value": true}
Explanation: 5 === 5 so this expression returns true.

Example 2

1
2
3
Input: func = () => expect(5).toBe(null)
Output: {"error": "Not Equal"}
Explanation: 5 !== null so this expression throw the error "Not Equal".

Example 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Input: func = () => expect(5).notToBe(null)
Output: {"value": true}
Explanation: 5 !== null so this expression returns true.

## Solution

### Method 1  JavaScript Closure

#### Intuition

Use a closure to capture the value and return an object with the required methods.

#### Approach

Return an object with `toBe` and `notToBe` methods, each throwing or returning as specified.

#### Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function expect(val) {
    return {
        toBe: function(other) {
            if (val === other) return true;
            throw new Error("Not Equal");
        },
        notToBe: function(other) {
            if (val !== other) return true;
            throw new Error("Equal");
        }
    };
}
#### Complexity - Time complexity: `O(1)` - 🧺 Space complexity: `O(1)`