[Leetcode] JS 30 To Be Or Not to Be
Question 2704
return object of functions / IIFE / throw error function
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 returnstrueif the two values===each other. If they are not equal, it should throw an error"Not Equal".notToBe(val)accepts another value and returnstrueif 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".
Example 3:
Input: func = () => expect(5).notToBe(null)
Output: {"value": true}
Explanation: 5 !== null so this expression returns true.
Solution
var expect = function(val) {
return {
toBe: function(expected) {
return (val === expected) ? true : (() => {throw new Error ("Not Equal")})()
},
notToBe: function(expected) {
return (val !== expected) ? true : (() => {throw new Error ("Equal")})()
}
};
};
Learning Point
One key concept demonstrated in this example is the ability to create a function that dynamically returns an object with specific methods. By doing so, we can encapsulate logic and provide an intuitive API for developers.
For instance, the expect function returns an object containing toBe and notToBe methods. These methods are dynamically tied to the value passed to expect. This design is common in libraries like Jest, where functions return objects with chainable methods to improve code readability and usability.
## below only defines the function ##
() => { throw new Error("Not Equal"); }
## below two lines will execute the function ##
const throwError = () => { throw new Error("Not Equal"); };
throwError(); // execute this function
An Immediately Invoked Function Expression (IIFE) is a JavaScript function that is executed immediately after it is defined. It is useful when we want to run some logic instantly without polluting the surrounding scope or defining extra variables.
## below is IIFE ##
(() => { throw new Error("Not Equal"); })();
throw KeywordThe throw keyword in JavaScript is used to intentionally raise an exception. It allows developers to signal that something unexpected has occurred, stopping the execution of code and delegating control to the nearest catch block.
In the context of this example, throw new Error("Not Equal") is used to create and throw an error when the condition fails. The Error object provides a message property that describes the issue, which is helpful for debugging and identifying problems during testing.
This approach is essential in testing scenarios because it clearly communicates when an assertion fails, providing meaningful feedback to developers.
Comments ()