We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

To Be Or Not To Be

Difficulty: Easy


Problem Description

Write a function expect that helps developers test their code. It should take in any value val and return an object with two functions: toBe(val) and notToBe(val). The toBe function should return true if the input value is strictly equal to the value passed into expect. If they are not equal, it should throw an error "Not Equal". The notToBe function should return true if the input value is not strictly equal to the value passed into expect. If they are equal, it should throw an error "Equal".


Key Insights

  • The solution involves creating an object with two methods to perform strict equality and inequality checks.
  • The toBe method checks if the two values are equal using the === operator.
  • The notToBe method checks if the two values are not equal using the !== operator.
  • Error handling is necessary for both methods to provide meaningful error messages.

Space and Time Complexity

Time Complexity: O(1) for both methods as they perform a constant time comparison. Space Complexity: O(1) since we are only using a fixed amount of space for the object methods.


Solution

We will define a function expect that takes a value and returns an object containing two methods: toBe and notToBe. Each method will perform the respective equality checks and return the appropriate result or throw an error.


Code Solutions

function expect(val) {
    return {
        toBe: function (otherVal) {
            if (val === otherVal) {
                return true;
            } else {
                throw new Error("Not Equal");
            }
        },
        notToBe: function (otherVal) {
            if (val !== otherVal) {
                return true;
            } else {
                throw new Error("Equal");
            }
        }
    };
}
← Back to All Questions