[Easy] LeetCode JS 30 - 2704. To Be Or Not To Be

March 5, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2704. To Be Or Not To Be

Question Prompt

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".
// Example 1
Input: func = () => expect(5).toBe(5)
Output: {"value": true}
Explanation: 5 === 5 so this expression returns true.

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

Solutions

First, create a function named expect. The expect function returns an object with two properties: toBe and notToBe. These properties are functions themselves.

The toBe property represents the "equality" assertion. If the value and val are not strictly equal, an Error with the message "Not Equal" is thrown, indicating that the assertion failed. If the value and val are strictly equal, the assertion passes, and true is returned.

The notToBe property represents the "inequality" assertion. If the value and val are strictly equal, an Error with the message "Equal" is thrown, indicating that the assertion failed. If the value and val are not strictly equal, the assertion passes, and true is returned.

var expect = function (val) {
  return {
    toBe: (value) => {
      if (value !== val) {
        throw new Error("Not Equal");
      } else {
        return true;
      }
    },
    notToBe: (value) => {
      if (value === val) {
        throw new Error("Equal");
      } else {
        return true;
      }
    },
  };
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee