TobilobaCodes – LeetCode Explorer

2704. To Be Or Not To Be

In this page, we will discuss LeetCode Problem 2704: To Be Or Not To Be. This problem requires you to write a function that helps developers test their code by comparing values.

πŸ“„ Problem Statement

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:

πŸ’‘ Example

expect(5).toBe(5); // true
expect(5).notToBe(5); // throws "Equal"

🧠 Explanation

This problem tests your understanding of closures and JavaScript functions. You’re required to return an object containing two methods that perform strict comparison checks, and throw custom errors when the expectations are not met.

βœ… My Solution


/**
 * @param {any} val
 * @return {{
 *   toBe: (val2: any) => boolean,
 *   notToBe: (val2: any) => boolean
 * }}
 */
var expect = function(val) {
    return {
        toBe: function(val2) {
            if (val === val2) return true;
            throw new Error("Not Equal");
        },
        notToBe: function(val2) {
            if (val !== val2) return true;
            throw new Error("Equal");
        }
    };
};