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:
toBe(val)
accepts another value and returnstrue
if the two values===
each other. If they are not equal, it should throw an error "Not Equal".notToBe(val)
accepts another value and returnstrue
if the two values!==
each other. If they are equal, it should throw an error "Equal".
π‘ 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");
}
};
};